/**
 * 对账模块-预付款申请首页JS
 *
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    companyCode: '#companyCode',
    supCodeOrName: '#supCodeOrName',
    applyNo: '#applyNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    status: '#status',
    syncState: '#syncState',
    oaProcessNo: '#oaProcessNo',
    pushOaUserName: '#pushOaUserName',
    poCode: '#poCode',
    btn_look: '#btn_look',
    btn_collection: '#btn_collection',
    btn_add: '#btn_add',
    btn_edit: '#btn_edit',
    btn_remove: '#btn_remove',
    btn_push_oa: '#btn_push_oa',
    btn_change: '#btn_change',
    btn_to_img: '#btn_to_img',
    btn_delete_img: '#btn_delete_img',
    tb: '#tb',
    tipsIndex: null,
    addOrEditDialog: null,
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    initPageComBoBox();

    initPageDataGrid();

    // initFileBox();
});


/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    // 初始化数据状态下拉框
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
            {label: '全部', value: -1},
            {label: '暂存', value: 1},
            {label: '待推送审批', value: 2},
            {label: '审批中', value: 3},
            {label: '审批拒绝', value: 4},
            {label: '付款完成', value: 5},
            {label: '审批作废', value: 6},
            {label: '待付款', value: 7},
            {label: '部分付款', value: 8},
            {label: '付款失败', value: 9},
            {label: '终止付款', value: 10},
        ],
        editable: false,
        panelHeight: 'auto'
    });

    initNecessaryDatas("pc/sys/company/rest/listAll");
    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        data:getNecessaryDataList("pc/sys/company/rest/listAll"),
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });
    initDict("sync_state");
    $(el.syncState).combobox({
        data:getDictList("sync_state"),
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });
}


/**
 * 初始化页面表格数据
 */
function initPageDataGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: '/pc/finance/paymentAdvance/apply/rest/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        title:"<span style='color: red'>*合同上约定了需要预付款的并且没有取得发票，此情况走预付款申请</span>",
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'status',
                    title: '数据状态',
                    width: 110,
                    sortable: true,
                    formatter: function (value,row) {
                        // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过) 6:OA审批作废
                        switch (value) {
                            case 1:
                                return '暂存';
                            case 2:
                                return '<span style="color: orange;">待推送审批</span>';
                            case 3:
                                return '<span style="color: blue;">审批中</span>';
                            case 4:
                                return '<span style="color: red;" title="'+row.oaAuditMessage+'">审批拒绝</span>';
                            case 5:
                                return '<span style="color: green;">付款完成</span>';
                            case 6:
                                return '<span style="color: red;" title="'+row.oaAuditMessage+'">审批作废</span>';
                            case 7:
                                return '<span style="color: mediumvioletred;">待付款</span>';
                            case 8:
                                return '<span style="color: orange;">部分付款</span>';
                            case 9:
                                return '<span style="color: red;" title="'+row.oaAuditMessage+'">付款失败</span>';
                            case 10:
                                return '<span style="color: red;" title="'+row.oaAuditMessage+'">终止付款</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'freezeStatus',
                    title: '冻结状态',
                    width: 100,
                    sortable: true,
                    formatter: function (value,row) {
                        // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
                        //数据状态 1:暂存 2:待推送 3:审批中 4:审批不通过 5:已支付 6:废弃 7：待付款 8：部分付款 9：付款失败
                        switch (value) {
                            case 0:
                                return '未冻结';
                            case 1:
                                return '<span style="color: orange;">冻结</span>';
                            case 2:
                                return '<span style="color: green;">解冻</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'changeStatus',
                    title: '变更状态',
                    width: 100,
                    sortable: true,
                    formatter: function (value,row) {
                        // 变更单审批状态；0-审批中  1-审批通过  2-审批驳回
                        switch (value) {
                            case 0:
                                return '审批中';
                            case 1:
                                return '<span style="color: green;">审批通过</span>';
                            case 2:
                                return '<span style="color: red;">审批驳回</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'urgentFlag',
                    title: '紧急程度',
                    width: 100,
                    sortable: true,
                    formatter: function (value,row) {
                        switch (value) {
                            case 0:
                                return '一般';
                            case 1:
                                return '<span style="color: red;">紧急</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'apApplyNo',
                    title: '申请单号',
                    width: 140,
                    sortable: true
                },
                // {
                //     field: 'oaType',
                //     title: '类型',
                //     width: 140,
                //     sortable: true
                // }
            ]
        ],
        columns: [
            [
                // {
                //     field: 'syncState',
                //     title: 'SAP同步状态',
                //     align: 'left',
                //     width: 100,
                //     formatter: function (value, row) {
                //         var msg="";
                //         if(row.syncMsg){
                //             msg=row.syncMsg.replace(/"/g,'&quot;')
                //         }
                //         if (!value) {
                //             return ""
                //         }
                //         // 1 未同步 2 已同步 3 变更未同步 4 同步失败
                //         if (value === 1) {
                //             return "未同步"
                //         }
                //         if (value === 2) {
                //             return "<span title='"+row.syncMsg+"' style='color: green'>同步成功</span>"
                //         }
                //         if (value === 3) {
                //             return '<span style="color: red;" onmouseover="showFailInfo(this)" onmouseout="closeShowTip()" data-msg="' + msg + '">同步失败</span>';
                //         }
                //     }
                // },
                {
                    field: 'oaProcessCode',
                    title: '共享申请单号',
                    width: 200,
                    sortable: true,
                    formatter: function (value, row) {
                        return shareTrack(row.oaProcessId, shareFormId.t_ap_applypaybill,value)
                    }
                    // formatter: function (value, row) {
                    //     return oaTrack(value, OaProcessType.PAYMENT_ADVANCE_APPLY)
                    // }
                },
                // {
                // field: 'oaProcessId',
                // title: '共享申请单号',
                // width: 100
                // },
                // {
                //     field: 'oaSubName',
                //     title: '预算科目',
                //     width: 120
                // },
                // {
                //     field: 'budInnerMoney',
                //     title: '预算内金额',
                //     width: 120,
                //     sortable: true,
                //     formatter: function (value) {
                //         if (!value) {
                //             return '';
                //         }
                //         return formatNumber(value, 2, 1);
                //     }
                // },
                // {
                //     field: 'budOutMoney',
                //     title: '预算外金额',
                //     width: 120,
                //     sortable: true,
                //     formatter: function (value) {
                //         if (!value) {
                //             return '0';
                //         }
                //         return formatNumber(value, 2, 1);
                //     }
                // },
                {
                    field: 'oaBorrowMoney',
                    title: '付款金额',
                    width: 120,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '0';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270,
                    sortable: true
                },
                {
                    field: 'supBankAccount',
                    title: '供应商账号',
                    width: 160,
                    sortable: true
                },
                {
                    field: 'supBankName',
                    title: '供应商银行名称',
                    width: 220,
                    sortable: true
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 60,
                    sortable: true
                },
                // {
                //     field: 'paymentWayCode',
                //     title: '付款方式',
                //     width: 200,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         return '(' + value + ')' + row.paymentWayDesc;
                //     }
                // },
                {
                    field: 'companyCode',
                    title: '付款公司',
                    width: 260,
                    sortable: true,
                    formatter: function (value, row) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                // {
                //     field: 'accountingDocument',
                //     title: '会计凭证号码',
                //     width: 100,
                //     sortable: true
                // },
                // {
                //     field: 'accountingYear',
                //     title: '会计年度',
                //     width: 60,
                //     sortable: true
                // },
                {
                    field: 'createUserName',
                    title: '制单人',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'createTime',
                    title: '申请时间',
                    width: 130,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'updateTime',
                    title: '最后更新时间',
                    width: 130,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'applyRemark',
                    title: '备注',
                    width: 260,
                    formatter: function (value) {
                        if (value) {
                            return '<span style="display: inline-block;width: 260px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title="' + value + '">' + value + '</span>';
                        }
                        return '';
                    }
                },
                {
                    field: 'oaAuditMessage',
                    title: '共享返回说明',
                    width: 130
                },
                {
                    field: 'emptyColumn',
                    title: '',
                    width: 20
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    detail(2)
                    setOperationLog("查看按钮", "预付款申请");

                }
            },
            '-',
            {
                text: '新增',
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    detail(0)
                    setOperationLog("新增按钮", "预付款申请");

                }
            },
            '-',
            {
                text: '编辑',
                iconCls: 'icon-edit',
                id: 'btn_edit',
                handler: function () {
                    detail(1)
                    setOperationLog("编辑按钮", "预付款申请");

                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_remove',
                handler: function () {
                    delPaaOrder();
                }
            },
            '-',
            {
                text: '提交审批',
                iconCls: 'icon-ok',
                id: 'btn_push_oa',
                handler: function () {
                    dataPushOa();
                }
            },
            "-",
            {
                text: '期初导入',
                iconCls: 'icon-import',
                id: 'btn_import',
                handler: function () {
                    advanceImport();
                }
            },

            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-redo',
            //     id: 'btn_export',
            //     handler: function () {
            //         dataExport();
            //     }
            // }, {
            //     text: '下载模板',
            //     iconCls: 'icon-download',
            //     id: 'btn_template',
            //     handler: function () {
            //         document.getElementById("frmExcel").action = '/files/download?fileName=' + encodeURI('advance_template.xlsx') +
            //             '&realName=' + encodeURI('预付款申请期初数据模板.xlsx') + '&ctype=templateFile';
            //         document.getElementById("frmExcel").submit();
            //     }
            // },
            // {
            //     text: '导入期初数据',
            //     iconCls: 'icon-download',
            //     id: 'btn_beginData',
            //     handler: function () {
            //         $("#fileUpload .filebox-label").click();
            //     }
            // },{
            //     text: '同步Sap',
            //     id: 'icon-sync',
            //     iconCls: 'icon-reload',
            //     handler: function () {
            //         syncSap();
            //     }
            // },
            {
                text: '审批通过',
                iconCls: 'icon-redo',
                id: 'btn-approval-agree',
                handler: function () {
                    approvalPass();
                }
            },
            '-',
            {
                text: '推送订单影像',
                iconCls: 'icon-ok',
                id: 'btn_to_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    if (Number(row.status)!==1){
                        topWin.layer.alert('只能选择暂存的记录', {icon: 0});
                        return false;
                    }
                    var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                    $.ajax({
                        url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/toImg',
                        type: 'POST',
                        data: {
                            appId: row.id
                        },
                        success: function () {
                            topWin.layer.close(loading);
                            topWin.layer.msg('推送成功', {icon: 1});
                            $(el.tb).edatagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.close(loading);
                            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            '-',
            {
                text: '删除订单影像',
                iconCls: 'icon-delete',
                id: 'btn_delete_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    if (Number(row.status)!==1){
                        topWin.layer.alert('只能选择暂存的记录', {icon: 0});
                        return false;
                    }
                    var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                    $.ajax({
                        url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/deleteImg',
                        type: 'POST',
                        data: {
                            appId: row.id
                        },
                        success: function () {
                            topWin.layer.close(loading);
                            topWin.layer.msg('删除成功', {icon: 1});
                            $(el.tb).edatagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.close(loading);
                            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            '-',
            {
                text: '查看订单影像',
                iconCls: 'icon-find',
                id: 'btn_look_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    const imageCode = row.poImgCode;
                    if (!imageCode) {
                        topWin.layer.alert("请先推送影像", {icon: 2, title: "温馨提示"});
                    } else {
                        $.ajax({
                            type: 'get',
                            url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
                            data: {
                                imageCode: imageCode
                            },
                            success: function (data) {
                                if (data) {
                                    window.open(data, "_blank");
                                }
                            },
                            error: function (error) {
                                topWin.layer.alert(error.responseJSON.message, {
                                    icon: 2,
                                    content: error.responseJSON.message
                                });
                            }
                        });
                    }
                }
            },
            '-',
            {
                text: '汇票催收',
                iconCls: 'icon-ok',
                id: 'btn_collection',
                handler: function () {
                    var row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选中一条记录', {icon: 0});
                        return false;
                    }
                    var id = row.id;
                    if (Number(row.sendEmailCollectionFlag)===1){
                        layer.confirm('已经汇票催收过,是否再次汇票催收？', {
                            btn: ['确定','取消'] //按钮
                        }, function(){
                            layer.closeAll()
                            var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                            $.ajax({
                                url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/sendEmailCollection',
                                method: "post",
                                data: {id: id},
                                success: function () {
                                    topWin.layer.msg('发送成功', {icon: 1});
                                    $(el.tb).datagrid('reload');
                                    $(el.tb).datagrid('clearSelections');
                                },
                                complete: function(data) {
                                    top.layer.close(loading);
                                },
                                error: function (data) {
                                    parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                                }
                            });
                            return false;
                        }, function(){
                            layer.closeAll()
                            return false;
                        });
                    }else {
                        parent.layer.confirm('是否确认汇票催收？', function (index) {
                            var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                            $.ajax({
                                url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/sendEmailCollection',
                                method: "post",
                                data: {id: id},
                                success: function () {
                                    parent.layer.close(index);
                                    $(el.tb).datagrid('reload');
                                    $(el.tb).datagrid('clearSelections');
                                },
                                complete: function(data) {
                                    top.layer.close(loading);
                                },
                                error: function (data) {
                                    parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                                }
                            });
                        });
                    }
                }
            },
            '-',
            {
                text: '发起变更单',
                iconCls: 'icon-ok',
                id: 'btn_change',
                handler: function () {
                    var rows = $(el.tb).datagrid('getSelections'), userId = $(el.userId).val();
                    if (rows.length===0) {
                        topWin.layer.alert('请选中一条记录', {icon: 0});
                        return false;
                    }
                    if (rows.length>1) {
                        topWin.layer.alert('只能选择一条记录，请取消多余的勾选项', {icon: 0});
                        return false;
                    }
                    if (Number(rows[0].status)!==9){
                        topWin.layer.alert('只能选择付款失败的记录', {icon: 0});
                        return false;
                    }
                    var id = rows[0].id;
                    var dialogElement = openDialog("editDialog", g.ctx + "pc/finance/payment/cod/apply/change?id="+id+'&businessType=1', {
                        title: "发起变更单",
                        width: '60%',
                        height: '80%',
                        cache: false,
                        modal: true,
                        border: false,
                        draggable: false,
                        shadow: false,
                        onClose: function () {
                            dialogElement.dialog('destroy');
                        },
                        buttons: [{
                            text: '提交',
                            iconCls: 'icon-save',
                            handler: function () {
                                topWin.frames['editDialog'].saveOrUpdate(function () {
                                    topWin.layer.msg('数据保存成功', {icon: 1});
                                    dialogElement.dialog('close');
                                    $(el.tb).datagrid('reload');
                                });
                            }
                        }, {
                            text: '关闭',
                            iconCls: 'icon-cancel',
                            handler: function () {
                                dialogElement.dialog('close');
                            }
                        }]
                    });
                }
            },
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("fin.payment.advance.apply.index");

            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var status = rows[rowIndex].status;
            var changeStatus = rows[rowIndex].changeStatus;
            var paymentWayCode = rows[rowIndex].paymentWayCode;
            if(paymentWayCode==='C'&&Number(status)===7){
                $(el.btn_collection).linkbutton('enable');
            }else {
                $(el.btn_collection).linkbutton('disable');
            }
            //数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
            switch (Number(status)) {
                case 1:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('enable');
                    $(el.btn_remove).linkbutton('enable');
                    $(el.btn_push_oa).linkbutton('enable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('enable');
                    $(el.btn_delete_img).linkbutton('enable');
                    break;
                case 2:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('enable');
                    $(el.btn_push_oa).linkbutton('enable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 3:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 4:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('enable');
                    $(el.btn_remove).linkbutton('enable');
                    $(el.btn_push_oa).linkbutton('enable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 5:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 6:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('enable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 7:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 8:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 9:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('enable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('enable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 10:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('enable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_push_oa).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_to_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                default:
                    break;
            }
            if (Number(status)===9){
                if (isBlank(changeStatus)){
                    $(el.btn_change).linkbutton('enable');
                }else if (Number(changeStatus)===2){
                    $(el.btn_change).linkbutton('enable');
                }else {
                    $(el.btn_change).linkbutton('disable');
                }
            }else {
                $(el.btn_change).linkbutton('disable');
            }
        }
    });
}
function syncSap(){
    let rows = $(el.tb).datagrid('getSelections');
    if(rows.length!=1){
        layer.msg("请选中一条记录"); return;
    }
    if(parseFloat(rows[0].oaBorrowMoney)<=0){
        layer.msg("付款金额小于等于0不能同步SAP");
        return false;
    }
    if ((rows[0].syncState != 1 && rows[0].syncState != 3) || rows[0].status!=5) {
        layer.alert("未同步或新建同步失败，且审批通过状态才可操作");
        return;
    }
    layer.confirm('确认同步SAP?', function(index) {
        let load = topWin.layer.load(0);
        $.ajax({
            url:"/fin/payment/advance/apply/rest/syncSap",
            data: {id : rows[0].id},
            success:function(data){
                if (data && data.state) {
                    $(el.tb).datagrid('load');
                    layer.close(index);
                    layer.alert(data.msg);
                }else {
                    layer.alert(data.msg);
                }
                topWin.layer.close(load);
            },
            error:function(){
                topWin.layer.close(load);
                layer.close(index);
                layer.alert("执行出错！");
            }
        })
    })
}

/**
 * 查看预付款申请
 */
function detail(optType) {
    var id = '';
    if (optType===otpTypeEnum.EDIT||optType===otpTypeEnum.COPY){
        var row = $(el.tb).datagrid('getSelected'), userId = $(el.userId).val();
        if (!row) {
            topWin.layer.alert('请选中一条记录', {icon: 0});
            return false;
        }
        id = row.id;
    }
    var url = g.ctx + 'pc/finance/paymentAdvance/apply/detail?id=' + id + '&optType='+optType;
    var buttons = [];
    if (optType===otpTypeEnum.COPY){
        buttons.push(
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }else {
        buttons.push(
            {
                text: '暂存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['addOrEditPaa'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.addOrEditDialog.dialog('close');
                    });
                }
            },
            // {
            //     text: '提交审核',
            //     iconCls: 'icon-ok',
            //     handler: function () {
            //         topWin.frames['addOrEditPaa'].dataSaveAndPushOa(function (data) {
            //             if(data === ''){
            //                 topWin.layer.msg('数据保存并推送成功', {icon: 1});
            //             }else {
            //                 topWin.layer.alert(data, {icon: 1});
            //             }
            //
            //             $(el.tb).datagrid('load');
            //             el.addOrEditDialog.dialog('close');
            //         });
            //     }
            // },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }
    el.addOrEditDialog = openDialog('addOrEditPaa', url, {
        title: (optType === otpTypeEnum.ADD ? "新增" :optType===otpTypeEnum.EDIT?"编辑":"查看"),
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addOrEditDialog.dialog('destroy');
        },
        buttons: buttons
    });
}

/**
 * 查看预付款申请
 */
function lookPaaOrder() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length !== 1) {
        topWin.layer.alert('请选择一条预付款申请单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/finance/paymentAdvance/apply/look?id=' + rows[0].id+'&companyType='+companyType;
    el.lookDialog = openDialog('lookPaaOrder', url, {
        title: '查看预付款申请',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 新增或编辑预付款申请单
 *
 * @param type 0:新增 1:编辑
 */
function addOrEditPaaOrder(type) {
    var title = '新增预付款申请', url = g.ctx + 'pc/finance/paymentAdvance/apply/add?companyType='+companyType;

    if (Number(type) === 1) {
        var rows = $(el.tb).datagrid('getSelections');
        if (rows.length !== 1) {
            topWin.layer.alert('请选择一条预付款申请单进行操作', {icon: 0});
            return false;
        }

        if (rows[0].status === 1 || rows[0].status === 4) {
            title = '编辑预付款申请';
            url = g.ctx + 'pc/finance/paymentAdvance/apply/edit?companyType='+companyType +'&id=' + rows[0].id;
        } else {
            topWin.layer.alert('预付款申请单的状态不支持编辑', {icon: 0});
            return false;
        }
    }
    el.addOrEditDialog = openDialog('addOrEditPaa', url, {
        title: title,
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addOrEditDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '暂存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['addOrEditPaa'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.addOrEditDialog.dialog('close');
                    });
                }
            },
            // {
            //     text: '提交审核',
            //     iconCls: 'icon-ok',
            //     handler: function () {
            //         topWin.frames['addOrEditPaa'].dataSaveAndPushOa(function (data) {
            //             if(data === ''){
            //                 topWin.layer.msg('数据保存并推送成功', {icon: 1});
            //             }else {
            //                 topWin.layer.alert(data, {icon: 1});
            //             }
            //
            //             $(el.tb).datagrid('load');
            //             el.addOrEditDialog.dialog('close');
            //         });
            //     }
            // },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.addOrEditDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 删除付款申请
 */
function delPaaOrder() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请选择预付款申请单进行操作', {icon: 0});
        return false;
    }

    var delIds = [];
    var set = new Set();
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
        // if (Number(item.status) !== 5 ) {
        //     delIds.push(item.id);
        // } else {
        //     topWin.layer.alert('预付款申请单号: ' + item.apApplyNo + '当前状态不允许删除', {icon: 0});
        //     return false;
        // }
        // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过) 6:OA审批作废
        debugger
        if (Number(item.status) === 6 ||Number(item.status) === 2 || Number(item.status) === 1|| Number(item.status) === 4) {
            delIds.push(item.id);
            set.add(Number(item.status))
        } else {
            topWin.layer.alert('预付款申请单号: ' + item.apApplyNo + '当前状态不允许删除', {icon: 0});
            return false;
        }
    }
    if(set.size>1){
        topWin.layer.alert('抱歉,请选择相同状态的单据删除', {icon: 0});
        return false;
    }
    let msg = '您确定要删除选中的记录吗?';
    if(set.has(1)){
        msg = '您确定要删除选中的记录吗?';
    }


    topWin.layer.confirm(msg, {icon: 3}, function (index) {
        topWin.layer.close(index);
        var loading = topWin.layer.msg('数据删除中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            type: 'POST',
            url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/data/del',
            data: {
                applyIds: JSON.stringify(delIds)
            },
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('数据删除成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 推送OA
 */
function dataPushOa() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length !== 1) {
        topWin.layer.alert('请选一条预付款申请单进行操作', {icon: 0});
        return false;
    }

    var item = rows[0];
    if(parseFloat(item.oaBorrowMoney)<=0){
        layer.msg("付款金额小于等于0不能同步OA");
        return false;
    }
    let msg = '您确定要将选中的记录进行审批吗';
    // if(Number(item.status) === 4){
    //     msg = '请确认是否将OA上对应的借款删除，请删除后再进行该操作?';
    // }else {
    //     msg = '您确定要将选中的记录进行审批吗?';
    // }
    // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
    if (Number(item.status) === 1 || Number(item.status) === 2 || Number(item.status) === 4) {
        topWin.layer.confirm(msg, {icon: 3}, function (index) {
            topWin.layer.close(index);
            var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
            $.ajax({
                type: 'POST',
                url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/push/oa',
                data: {
                    applyId: item.id,
                    companyType: companyType
                },
                success: function () {
                    topWin.layer.close(loading);
                    topWin.layer.msg('数据推送成功', {icon: 1});
                    $(el.tb).datagrid('reload');
                },
                error: function (data) {
                    parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                }
            });
        });
    } else {
        topWin.layer.alert('预付款申请单号: ' + item.apApplyNo + '当前状态不允许推送审批', {icon: 0});
        return false;
    }
}


/**
 * 数据导出
 */
function dataExport() {
    var url = g.ctx + 'fin/payment/advance/apply/rest/data/export' +
        '?applyNo=' + $.trim($(el.applyNo).val()) +
        '&supCodeOrName=' + $.trim($(el.supCodeOrName).val()) +
        '&oaProcessCode=' + $.trim($(el.oaProcessNo).val()) +
        '&poCode=' + $.trim($(el.poCode).val()) +
        '&pushOaUserName=' + $.trim($(el.pushOaUserName).val()) +
        '&companyCode=' + $(el.companyCode).combobox('getValue') +
        '&status=' + $(el.status).combobox('getValue') +
        '&createTimeStart=' + $(el.createTimeStart).datebox('getValue') +
        '&createTimeEnd=' + $(el.createTimeEnd).datebox('getValue');
    window.open(url);
}


/**
 * 数据查询
 */
function searchPaaData() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.applyNo = $.trim($(el.applyNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.createUserName = $.trim($('#createUserName').val());
    queryParams.oaBorrowMoneyBegin = $.trim($('#oaBorrowMoneyBegin').numberbox('getValue'));
    queryParams.oaBorrowMoneyEnd = $.trim($('#oaBorrowMoneyEnd').numberbox('getValue'));
    queryParams.poCode = $.trim($(el.poCode).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.oaType = $('#oaType').val();
    queryParams.isOa = $('#isOa').val();
    queryParams.contractCode = $('#contractCode').val();
    queryParams.oaSubName = $('#oaSubName').val();
    queryParams.oaProcessCode = $('#oaProcessCode').val();
    queryParams.syncState = $('#syncState').val();
    queryParams.accountingDocument = $('#accountingDocument').val();
    queryParams.oaProcessId = $.trim($('#oaProcessId').val());

    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetPaaSearch() {
    $(el.applyNo).val('');
    $(el.supCodeOrName).val('');
    $('#createUserName').val('');
    $('#oaBorrowMoneyBegin').numberbox('setValue', '');
    $('#oaBorrowMoneyEnd').numberbox('setValue', '');
    $(el.poCode).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $('#oaType').val('');
    $('#isOa').combobox('setValue', '');
    $('#contractCode').val('');
    $('#oaSubName').val('');
    $('#oaProcessCode').val('');
    $('#accountingDocument').val('');
    $('#oaProcessId').val('');
    searchPaaData();
}

/**
 * 审批通过
 *
 */
function approvalPass() {
    var rows = $(el.tb).datagrid('getSelections'),  ids = [];

    if(rows.length === 0){
        layer.msg("请至少选择一行数据", {icon: 0});
        return false;
    }
    var rowsFilter=rows.filter(item=>item.isOa!=1)
    // if(rowsFilter.length!=0){
    //     layer.msg("只能手工审批通过“是否OA补录”为是的单据", {icon: 0});
    //     return false;
    // }

    ids=rows.map(item=>item.id).join(',')

    topWin.layer.confirm('您确定要通过吗?', {icon: 3}, function (index) {
        var load = topWin.layer.load(0);
        $.ajax({
            url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/approval/pass',
            type: 'POST',
            data: {
                ids: ids,
            },
            success: function () {
                topWin.layer.close(load);
                topWin.layer.close(index);
                topWin.layer.msg('审批成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(load);
                topWin.layer.close(index);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}

/**
 * 显示title
 *
 * @param ele 当前DOM节点
 */
function showFailInfo(ele) {
    el.tipsIndex = layer.tips($(ele).data('msg'), ele, {
        tips: [1, '#3595CC'],
        time: 0
    });
}


/**
 * 关闭tip
 */
function closeShowTip() {
    if(null !== el.tipsIndex){
        layer.close(el.tipsIndex);
    }
}

function advanceImport(){
    var importDialog = openImportExcelDialog('static/excel/预付款导入模版.xlsx','预付款期初导入',function(file){
        let formData = new FormData();
        formData.append("file", file);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/import',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {

                if (data === 'ok') {
                    topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearSelections');
                        topWin.layer.close(idx);
                        importDialog.dialog('close');
                    });
                } else {
                    topWin.layer.confirm('部分导入成功,是否下载未成功数据?', function (index) {
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearSelections');
                        topWin.layer.close(index);
                        window.location.href = g.ctx + 'pc/sys/file/rest/download/' + data
                    });
                }
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}
