/**
 * 对账模块-付款申请首页JS
 *
 * Created by li.kui on 2020/9/15.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    restrictFlag: '#restrictFlag',
    companyCode: '#companyCode',
    supCodeOrName: '#supCodeOrName',
    applyNo: '#applyNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    status: '#status',
    oaProcessNo: '#oaProcessNo',
    pushOaUserName: '#pushOaUserName',
    btn_look: '#btn_look',
    // btn_collection: '#btn_collection',
    btn_add: '#btn_add',
    btn_edit: '#btn_update',
    btn_remove: '#btn_delete',
    btn_confirm: '#btn_confirm',
    // btn_clear_oa: '#btn_clear_oa',
    btn_change: '#btn_change',
    btn_push_img: '#btn_push_img',
    btn_delete_img:'#btn_delete_img',
    tb: '#tb',
    poCode: '#poCode',
    addOrEditDialog: null,
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


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

    initPageDataGrid();
});


/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    // 初始化数据状态下拉框
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 数据状态 1:暂存待提交 2:待推送OA审批 3:OA审批中 4:OA审批拒绝 5:付款完成(OA审批通过)
            //数据状态 1:暂存 2:待推送 3:审批中 4:审批不通过 5:已支付 6:废弃 7：待付款 8：部分付款 9：付款失败
            {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'
    });

    initDict('payment_method')
    initDict('payment_way')
    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: '--- 请选择 ---'
    });
}


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

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        url: g.ctx + 'pc/contract/payment/rest/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        title:"<span style='color: red'>*服务已验收或物料已入库并且取得了发票，此情况走对账付款申请</span>",
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {},
        // frozenColumns: [
        //     [
        //
        //     ]
        // ],
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'status',
                    title: '数据状态',
                    width: 90,
                    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 1:
                                return '暂存';
                            // case 2:
                            //     return '<span style="color: orange;">待推送审批</span>';
                            case 3:
                                return '<span style="color: blue;" title="'+row.oaProcessMessage+'">审批中</span>';
                            case 4:
                                return '<span style="color: red;" title="'+row.oaProcessMessage+'">审批拒绝</span>';
                            case 5:
                                return '<span style="color: green;" title="'+row.oaProcessMessage+'">付款完成</span>';
                            case 6:
                                return '<span style="color: red;" title="'+row.oaProcessMessage+'">审批作废</span>';
                            case 7:
                                return '<span style="color: blue;" title="'+row.oaProcessMessage+'">待付款</span>';
                            case 8:
                                return '<span style="color: orange;" title="'+row.oaProcessMessage+'">部分付款</span>';
                            case 9:
                                return '<span style="color: red;" title="'+row.oaProcessMessage+'">付款失败</span>';
                            case 10:
                                return '<span style="color: red;" title="'+row.oaProcessMessage+'">终止付款</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'freezeStatus',
                    title: '冻结状态',
                    width: 80,
                    sortable: true,
                    formatter: function (value,row) {
                        switch (value) {
                            case 0:
                                return '未冻结';
                            case 1:
                                return '<span style="color: red;">冻结</span>';
                            case 2:
                                return '<span style="color: green;">解冻</span>';
                            default:
                                return '未冻结';
                        }
                    }
                },
                {
                    field: 'changeStatus',
                    title: '变更状态',
                    width: 80,
                    sortable: true,
                    formatter: function (value,row) {
                        switch (value) {
                            case 0:
                                return '<span style="color: blue;">审批中</span>';
                            case 2:
                                return '<span style="color: red;">审批驳回</span>';
                            case 1:
                                return '<span style="color: green;">审批通过</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'urgentFlag',
                    title: '紧急程度',
                    width: 80,
                    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: 'paymentType',
                    title: '付款类型',
                    width: 80,
                    sortable: true,
                    formatter: function (value,row) {
                        switch (value) {
                            case '01':
                                return '预付款';
                            case '02':
                                return '进度款';
                            case '03':
                                return '验收款';
                            case '04':
                                return '质保款';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'oaProcessCode',
                    title: '共享流程号',
                    width: 150,
                    sortable: true,
                    formatter: function (value, row) {
                        return shareTrack(row.oaProcessId, shareFormId.t_ap_applypaybill,value)
                    }
                },
                {
                    field: 'oaBorrowMoney',
                    title: '付款金额',
                    width: 90,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 250,
                    sortable: true
                },
                {
                    field: 'supBankAccount',
                    title: '供应商账号',
                    width: 130,
                    sortable: true
                },
                {
                    field: 'supBankName',
                    title: '供应商银行名称',
                    width: 220,
                    sortable: true
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 60,
                    sortable: true
                },
                {
                    field: 'paymentWayCode',
                    title: '付款方式',
                    width: 80,
                    sortable: true,
                    formatter: function (value, row) {
                        return getDicName('payment_way',value);
                    }
                },
                {
                    field: 'companyCode',
                    title: '付款公司',
                    width: 260,
                    sortable: true,
                    formatter: function (value, row) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    field: 'createUserName',
                    title: '申请人',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'createTime',
                    title: '申请时间',
                    width: 120,
                    sortable: true,
                    formatter: function (value) {
                        if(!value){
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'updateTime',
                    title: '最后更新时间',
                    width: 120,
                    sortable: true,
                    formatter: function (value) {
                        if(!value){
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'oaProcessId',
                    title: '共享申请单号',
                    width: 140
                },
                {
                    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: 'emptyColumn',
                    title: '',
                    width: 20
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    addOrEditPcaOrder(2)
                    setOperationLog("查看按钮", "MRO合同付款申请");

                }
            },
            '-',
            {
                text: '新增',
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    addOrEditPcaOrder(0);
                }
            },
            '-',
            {
                text: '编辑',//只有1暂存，4驳回的才允许编辑
                iconCls: 'icon-edit',
                id: 'btn_update',
                handler: function () {
                    addOrEditPcaOrder(1);
                    setOperationLog("编辑按钮", "MRO合同付款申请");

                }
            },
            '-',
            {
                text: '删除',//只有1暂存，6作废的才允许删除
                iconCls: 'icon-remove',
                id: 'btn_delete',
                handler: function () {
                    delPcaOrder();
                }
            },
            '-',
            {
                text: '提交审批',//只有1暂存，4驳回的才允许提交审批
                iconCls: 'icon-ok',
                id: 'btn_confirm',
                handler: function () {
                    dataPushOa();
                }
            }, '-',
            {
                text: '发起变更单',//付款失败的9
                iconCls: 'icon-ok',
                id: 'btn_change',
                handler: function () {
                    var row = $(el.tb).datagrid('getSelected'), userId = $(el.userId).val();
                    if (!row) {
                        topWin.layer.alert('请选中一条记录', {icon: 0});
                        return false;
                    }
                    var id = row.id;
                    var dialogElement = openDialog("editDialog", g.ctx + "pc/contract/payment/page/change?id="+id, {
                        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');
                            }
                        }]
                    });
                }
            },
            '-',
            {
                text: '推送影像',
                iconCls: 'icon-ok',
                id: 'btn_push_img',
                handler: function () {
                    pushImage();
                }
            },
            '-',{
                text: '删除影像',
                id: 'btn_delete_img',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteImage();
                }
            },
            {
                text: '查看影像',
                iconCls: 'icon-find',
                id: 'btn_look_img',
                handler: function () {
                    showImage();
                }
            },
            // {
            //     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/payment/cod/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: '温馨提示'});
            //                     }
            //                 });
            //                 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/payment/cod/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: '温馨提示'});
            //                     }
            //                 });
            //             });
            //         }
            //
            //     }
            // },
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("MRO_Payment_apply");
            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var status = rows[rowIndex].status;
            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_confirm).linkbutton('enable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_remove).linkbutton('disable');
                    $(el.btn_confirm).linkbutton('enable');
                    $(el.approval).linkbutton('enable');
                    $(el.btn_clear_oa).linkbutton('enable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_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_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    if (rows[rowIndex].changeStatus !== 0) {
                        $(el.btn_change).linkbutton('enable');
                    } else {
                        $(el.btn_change).linkbutton('disable');
                    }
                    $(el.btn_push_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                case 10:
                    $(el.btn_look).linkbutton('enable');
                    $(el.btn_add).linkbutton('disable');
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    $(el.btn_confirm).linkbutton('disable');
                    $(el.approval).linkbutton('disable');
                    $(el.btn_clear_oa).linkbutton('disable');
                    $(el.btn_change).linkbutton('disable');
                    $(el.btn_push_img).linkbutton('disable');
                    $(el.btn_delete_img).linkbutton('disable');
                    break;
                default:
                    break;
            }
        }
    });
}

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/cod/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 lookPcaOrder() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length !== 1) {
        topWin.layer.alert('请选择一条对账付款申请单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/finance/payment/cod/apply/look?id=' + rows[0].id+'&companyType='+companyType;
    el.lookDialog = openDialog('lookPaymentCodApplyOrder', 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 addOrEditPcaOrder(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/contract/payment/page/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['addOrEditPca'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {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('addOrEditPca', 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 delPcaOrder() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请选择付款申请单进行操作', {icon: 0});
        return false;
    }

    var delIds = [];
    let set = new Set()
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        // 数据状态 1:暂存待提交 2:待审批 3:审批中 4:审批拒绝 5:付款完成
        // if(Number(item.status) !== 5 ){
        //     delIds.push(item.id);
        // }else {
        //     topWin.layer.alert('对账付款申请单号: ' + item.cpApplyNo + '当前状态不允许删除', {icon: 0});
        //     return false;
        // }
        if (Number(item.status) === 6 || Number(item.status) === 4 ||Number(item.status) === 2 || Number(item.status) === 1) {
            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(4)){
    //     msg = '请确认是否将OA上对应的借款删除，请删除后再进行该操作?';
    // }else 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/contract/payment/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 clearOaNumber(){
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请至少选一条对账付款申请单进行操作', {icon: 0});
        return false;
    }
    debugger;
    var ids = [];
    var statusArray = [];
    var oaProcessCodes = [];
    rows.forEach(function(row) {
        var status = row['status']; // 假设status是每行的属性名
        ids.push(row['id']);
        statusArray.push(status);
        oaProcessCodes.push(row['oaProcessCode']);
    });

    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if (rows[i].status != 4 ){
            topWin.layer.alert('选择的数据审批状态必须都是审批驳回状态', {icon: 0});
            return false;
        }
    }
    //判断选择的审批状态是不是全部为审批驳回
    // 判断选择的流程code是不是同一个防止误删除
    if(!areAllValuesEqual(oaProcessCodes)){
        topWin.layer.alert('选择的数据OA代码必须相同', {icon: 0});
        return false;
    }
//清除付款流程的OA流程编号和code 状态修改为待提交（状态是否修改代讨论）
    let msg = '您确定要将选中的记录进行清除OA审批编号吗?';
    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/payment/cod/apply/rest/clear/oaNumber',
            data: {
                ids: ids.join(',')
            },
            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: '温馨提示'});
            }
        });
    });
}

function areAllValuesEqual(arr) {
    return arr.every(function(value) {
        return value === arr[0];
    });
}

//清除OA审批编号和code

let confirmFlag = false;
/**
 * 推送OA
 */
function dataPushOa() {
    if(confirmFlag) {
        topWin.layer.alert('数据正在处理中，请稍后操作！', {icon: 0});
        return false;
    }
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请至少选一条对账付款申请单进行操作', {icon: 0});
        return false;
    }
    var ids = [];
    var oaProcessCode = '';
    var advancePaymentFlag = '';
    var paymentWayCode = '';
    var companyCode = '';
    var faSupplier = '';
    var acceptanceMethod = '';
    var currencyCode = '';
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if(parseFloat(item.oaBorrowMoney)<=0){
            layer.msg('申请单号：'+item.apApplyNo+"，付款金额小于等于0不能同步共享");
            return false;
        }
        if(Number(item.status) !== 1 && Number(item.status) !== 2 && Number(item.status) !== 4){
            topWin.layer.alert('申请单号: ' + item.apApplyNo + '当前状态不允许推送审批', {icon: 0});
            return false;
        }
        ids.push(item.id)
        if (oaProcessCode&&rows[i].oaProcessCode){
            if(i !== 0 && oaProcessCode !== rows[i].oaProcessCode){
                topWin.layer.alert('共享流程号不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].oaProcessCode){
            oaProcessCode = rows[i].oaProcessCode;
        }
        if (advancePaymentFlag&&rows[i].advancePaymentFlag){
            if(i !== 0 && advancePaymentFlag !== rows[i].advancePaymentFlag){
                topWin.layer.alert('是否提前付款不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].advancePaymentFlag){
            advancePaymentFlag = rows[i].advancePaymentFlag;
        }

        if (paymentWayCode&&rows[i].paymentWayCode){
            if(i !== 0 && paymentWayCode !== rows[i].paymentWayCode){
                topWin.layer.alert('付款方式不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].paymentWayCode){
            paymentWayCode = rows[i].paymentWayCode;
        }
        if (companyCode&&rows[i].companyCode){
            if(i !== 0 && companyCode !== rows[i].companyCode){
                topWin.layer.alert('公司不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].companyCode){
            companyCode = rows[i].companyCode;
        }
        if (faSupplier&&rows[i].faSupplier){
            if(i !== 0 && faSupplier !== rows[i].faSupplier){
                topWin.layer.alert('公司不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].faSupplier){
            faSupplier = rows[i].faSupplier;
        }
        if (acceptanceMethod&&rows[i].acceptanceMethod){
            if(i !== 0 && acceptanceMethod !== rows[i].acceptanceMethod){
                topWin.layer.alert('承兑期限不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].currencyCode){
            currencyCode = rows[i].currencyCode;
        }
        if (acceptanceMethod&&rows[i].currencyCode){
            if(i !== 0 && currencyCode !== rows[i].currencyCode){
                topWin.layer.alert('币种不一致，不允许提交', {icon: 0});
                return false;
            }
        }
        if (rows[i].currencyCode){
            currencyCode = rows[i].currencyCode;
        }
    }

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


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

/**
 * 审批通过
 */
function approvalPass() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.alert('请选择[是否为OA补录]为是的数据', {icon: 0});
        return false;
    }
    var NoMatchArray = rows.filter(item=>item.isOa===0);
    if(NoMatchArray.length>0){
        topWin.layer.alert('请选择[是否为OA补录]为是的数据', {icon: 0});
        return false;
    }

    var ids = [];
    for (let i = 0; i < rows.length; i++) {
        ids.push(rows[i].id)
    }

    topWin.layer.confirm('您确定要通过吗?', {icon: 3}, function (index) {
        var load = topWin.layer.load(0);
        $.ajax({
            url: g.ctx + 'fin/payment/cod/apply/rest/approvalPass',
            type: 'POST',
            dataType: "json",
            contentType: 'text/plain;charset=UTF-8',
            data: JSON.stringify(ids),
            success: function (result) {
                console.log('data',result)
                var state = result.state;
                if(state){
                    topWin.layer.close(load);
                    topWin.layer.close(index);
                    topWin.layer.msg('审批成功', {icon: 1});
                    $(el.tb).datagrid('reload');
                }else {
                    topWin.layer.close(load);
                    topWin.layer.close(index);
                    topWin.layer.msg('审批失败', {icon: 2});
                }
            },
            error: function (data) {
                topWin.layer.close(load);
                topWin.layer.close(index);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 数据查询
 */
function searchPcaData() {
    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.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.oaProcessCode = $('#oaProcessCode').val();
    queryParams.poCode = $.trim($(el.poCode).val());
    queryParams.contractCode = $.trim($('#contractCode').val());
    queryParams.oaSubName = $('#oaSubName').val();
    queryParams.syncState = $('#syncState').val();
    queryParams.accountingDocument = $('#accountingDocument').val();
    queryParams.invoiceNo = $('#invoiceNo').val();
    queryParams.oaProcessId = $.trim($('#oaProcessId').val());

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


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

/**
 推送影像
 */
function pushImage() {
    let tableData = $(el.tb).datagrid('getSelections');
    tableData = tableData.filter(item => {
        // 状态是“暂存、共享审批驳回“，才允许执行
        return item.status === 1 || item.status === 4;
    });
    if (tableData.length === 0) {
        layer.msg("请选择一条记录");
        return;
    }
    for(var i = 0; i < tableData.length; i++) {
        var item = tableData[i];
        if (item.paymentType === "04") {
            layer.msg("质保款阶段不可推送影像");
            return;
        }
    }
    for (let i in tableData) {
        if (tableData[i].imgCode) {
            topWin.layer.alert("申请单号：" + tableData[i].apApplyNo + "，已经推送影像，请勿重复推送" +
                "<br><span style='color: rgb(243, 155, 18)'>如要重推，请先删除</span>", {icon: 0});
            return;
        }
    }
    const pushIds = tableData.map(item => {
        return item.id;
    });
    const load = topWin.layer.load(0);
    $.ajax({
        type: 'post',
        url: g.ctx + 'pc/contract/payment/rest/pushImage',
        data: {
            pushIds: pushIds.join(',')
        },
        success: function () {
            topWin.layer.close(load);
            topWin.layer.msg('影像推送成功', {icon: 1});
            $(el.tb).datagrid('reload');
        },
        error: function (error) {
            topWin.layer.close(load);
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}

/**
 * 删除影像
 */
function deleteImage() {
    let tableData = $(el.tb).datagrid('getSelections');
    if (tableData.length === 0) {
        layer.msg("请选择一条记录");
        return;
    }
    tableData = tableData.filter(item => item.imgCode);
    if (tableData.length === 0) {
        layer.msg("所选记录中无影像信息可删除");
        return;
    }
    for(var i = 0; i < tableData.length; i++) {
        var item = tableData[i];
        if (item.paymentType === "04") {
            layer.msg("质保款阶段不可删除影像");
            return;
        }
    }

    topWin.layer.confirm('您确定删除选中数据的影像数据吗?', {icon: 3}, function (index) {
        const load = topWin.layer.load(0);
        const deleteIds = tableData.map(item => {
            return item.id;
        });
        $.ajax({
            type: 'post',
            url: g.ctx + 'pc/contract/payment/rest/deleteImage',
            data: {
                deleteIds: deleteIds.join(',')
            },
            success: function () {
                topWin.layer.close(load);
                topWin.layer.close(index);
                topWin.layer.msg('已经删除', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (error) {
                topWin.layer.close(load);
                topWin.layer.close(index);
                topWin.layer.alert(error.responseJSON.message, {
                    icon: 2,
                    content: error.responseJSON.message
                });
            }
        });
    });
}

/**
 * 查看影像
 */
function showImage(){
    const tableData = $(el.tb).datagrid('getSelections');
    if (tableData.length === 0) {
        layer.msg("请选择一条记录");
        return;
    }
    if (tableData.length > 1) {
        layer.msg("请勿多选");
        return;
    }
    const imageCode = tableData[0].poImgCode;
    if (!imageCode) {
        layer.msg("该记录无影像信息");
        return;
    }
    $.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
            });
        }
    });
}