/**
 * 对账模块-财务到票确认首页JS
 *
 * Created by li.kui on 2020/8/28.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    btn_finance_confirm: '#btn_finance_confirm',
    paymentExpireDateStart: '#paymentExpireDateStart',
    paymentExpireDateEnd: '#paymentExpireDateEnd',
    btn_fin_post: '#btn_fin_post',
    btn_finance_confirm_cancel: '#btn_finance_confirm_cancel',
    btn_fin_remove: '#btn_fin_remove',
    financeConfirmUserName: '#financeConfirmUserName',
    companyCode: '#companyCode',
    supCodeOrName: '#supCodeOrName',
    invoiceApplyNo: '#invoiceApplyNo',
    invoiceVoucher: '#invoiceVoucher',
    tbFile: '#tbFile',
    purchaseGroup: '#purchaseGroup',
    paperlessFlag: '#paperlessFlag',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    createUserName: '#createUserName',
    oaProcessNo: '#oaProcessNo',
    status: '#status',
    postStatus: '#postStatus',
    currencyCode: '#currencyCode',
    orderType: '#orderType',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    tb: '#tb',
    optConfirmDialog: null,
    financePostDialog: null,
    lookDialog: null,
    finPostDialog: '#finPostDialog',
    iaId: '#iaId',
    invoicePostDate: '#invoicePostDate',
    statementType: '#statementType',
    zeroDate: '#zeroDate',
    voucherHead: '#voucherHead',
    voucherHeadText: '#voucherHeadText',
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/company/rest/listAll')
    initComBoBoxData();

    loadGrid();

    $(el.invoicePostDate).datebox({
        value: moment().format('YYYY-MM-DD'),
    });
});


/**
 * 初始化页面下拉框数据
 */
function initComBoBoxData() {
    // 初始化数据状态下拉框
    // 开票申请单状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '待财务确认发票', value: 7},
            {label: '发票已确认', value: 9}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    // 初始化过账状态下拉框
    // 过账状态 -1:全部 1:暂存 2:待过账 3:过账失败 4:过账成功
    $(el.postStatus).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            {label: '全部', value: -1},
            {label: '暂存', value: 1},
            {label: '待预制', value: 2},
            {label: '预制失败', value: 3},
            {label: '预制成功', value: 4},
            {label: '过账成功', value: 5},
            {label: '无需过账', value: 6},
            {label: '已冲销', value: 7}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    // 初始化公司名称下拉框
    $(el.companyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll?isAuthority=0',
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            $(this).combobox("select", $('#deptCode').val());
        }
    });
    //初始化日期
    var months = [];

    for (let i = 1; i <= 12; i++) {
        let paddedNumber = i.toString().padStart(2, '0');
        months.push({
            label: paddedNumber,
            value: paddedNumber
        });
    }

    $('#accountStatementMonth').combobox({
        data: months,
        valueField: 'value',
        textField: 'label'
    });

    // 初始化收付条件代码下拉框
    // $(el.voucherHead).combobox({
    //     url: g.ctx + 'fin/common/rest/find/payment/condition/code',
    //     editable: false,
    //     panelHeight: 280,
    //     panelWidth: 300,
    //     valueField: 'textCode',
    //     textField: 'textDesc',
    //     prompt: '--- 请选择 ---',
    //     onSelect: function (data) {
    //         $(el.voucherHeadText).textbox('setValue', data.textDesc);
    //     }
    // });

    // 初始化单据类型下拉框
    // 单据类型 -1:全部 1:材料类 2:运费类
    $(el.orderType).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            {label: '全部', value: -1},
            {label: '材料类', value: 1},
            {label: '运费类', value: 2}
        ],
        editable: false,
        panelHeight: 'auto'
    });
}


/**
 * 初始化页面表格
 */
function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    var status=$("#status").val();
    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            roleType: 2,
            companyCode: $('#deptCode').val(),
            status: status
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'status',
                    title: '数据状态',
                    width: 115,
                    sortable: true,
                    exportEnum:[
                        {code:1,codeWithDesc:'暂存发票'},
                        {code:2,codeWithDesc:'待采购确认发票'},
                        {code:3,codeWithDesc:'采购拒绝发票'},
                        {code:4,codeWithDesc:'待推送OA审批'},
                        {code:5,codeWithDesc:'OA审批中'},
                        {code:6,codeWithDesc:'OA审批不通过'},
                        {code:7,codeWithDesc:'待财务确认发票'},
                        {code:8,codeWithDesc:'财务驳回发票'},
                        {code:9,codeWithDesc:'发票已确认'},
                    ],
                    formatter: function (value) {
                        // 开票申请单状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
                        switch (Number(value)) {
                            case 1:
                                return '暂存发票';
                            case 2:
                                return '<span style="color: orange;">待采购确认发票</span>';
                            case 3:
                                return '<span style="color: red;">采购拒绝发票</span>';
                            case 4:
                                return '<span style="color: orange;">待推送OA审批</span>';
                            case 5:
                                return '<span style="color: blue;">OA审批中</span>';
                            case 6:
                                return '<span style="color: red;">OA审批不通过</span>';
                            case 7:
                                return '<span style="color: orange;">待财务确认发票</span>';
                            case 8:
                                return '<span style="color: red;">财务驳回发票</span>';
                            case 9:
                                return '<span style="color: green;">发票已确认</span>';
                            default:
                                return '';
                        }
                    }
                },
                // {
                //     field: 'foreignCurrencyAddFlag',
                //     title: '外币资料交接',
                //     width: 100,
                //     sortable: true,
                //     exportEnum:[
                //         {code:0,codeWithDesc:'否'},
                //         {code:1,codeWithDesc:'是'}
                //     ],
                //     formatter:function (value) {
                //         if(value === 0){
                //             return "否"
                //         }else{
                //             return "<span style='color: green;'>是</span>"
                //         }
                //     }
                // },
                {
                    field: 'paperlessFlag',
                    title: '是否无纸化',
                    width: 100,
                    exportEnum:[
                        {code:0,codeWithDesc:'否'},
                        {code:1,codeWithDesc:'是'}
                    ],
                    formatter:function (value) {
                        if(value === 0){
                            return "否"
                        }else{
                            return "<span style='color: green;'>是</span>"
                        }
                    }
                },
                {
                    field: 'postStatus',
                    title: '过账状态',
                    width: 80,
                    sortable: true,
                    exportEnum:[
                        {code:1,codeWithDesc:'暂存'},
                        {code:2,codeWithDesc:'待预制'},
                        {code:3,codeWithDesc:'预制失败'},
                        {code:4,codeWithDesc:'预制成功'},
                        {code:5,codeWithDesc:'过账成功'},
                        {code:6,codeWithDesc:'无需过账'},
                        {code:7,codeWithDesc:'已冲销'}
                    ],
                    formatter: function (value, row) {
                        // 过账状态 1:暂存 2:待预制 3:预制失败 4:预制成功 5:过账成功 6:无需过账 7:已冲销
                        switch (Number(value)) {
                            case 1:
                                return '暂存';
                            case 2:
                                return '<span style="color: orange;">待预制</span>';
                            case 3:
                                return '<span style="color: red;" title="'+row.syncMessage+'">预制失败</span>';
                            case 4:
                                return '<span style="color: blue;">预制成功</span>';
                            case 5:
                                return '<span style="color: green;">过账成功</span>';
                            case 6:
                                return '<span style="color: grey;">无需过账</span>';
                            case 7:
                                return '<span  style="color: red;">已冲销</span>';
                            default:
                                return '';
                        }
                    }
                },
                // {
                //     field: 'strikeStatus',
                //     title: '冲账状态',
                //     width: 80,
                //     sortable: true,
                //     exportEnum:[
                //         {code:0,codeWithDesc:'暂存'},
                //         {code:1,codeWithDesc:'冲账成功'},
                //         {code:2,codeWithDesc:'冲账失败'},
                //         {code:3,codeWithDesc:'无需冲账'}
                //     ],
                //     formatter: function (value, row) {
                //         // 冲账状态 0-待冲账；1-冲账成功；2-冲账失败；3-无需冲账
                //         switch (Number(value)) {
                //             case 0:
                //                 return '暂存';
                //             case 1:
                //                 return '<span style="color: green;">冲账成功</span>';
                //             case 2:
                //                 return '<span style="color: red;" title="'+row.syncStrikeMessage+'">冲账失败</span>';
                //             case 3:
                //                 return '<span style="color: blue;">无需冲账</span>';
                //             default:
                //                 return '';
                //         }
                //     }
                // },
                // {
                //     field: 'deductionStatus',
                //     title: '扣款状态',
                //     width: 80,
                //     sortable: true,
                //     exportEnum:[
                //         {code:0,codeWithDesc:'暂存'},
                //         {code:1,codeWithDesc:'扣款成功'},
                //         {code:2,codeWithDesc:'扣款失败'},
                //         {code:3,codeWithDesc:'无需扣款'}
                //     ],
                //     formatter: function (value, row) {
                //         // 冲账状态 0-待冲账；1-冲账成功；2-冲账失败；3-无需冲账
                //         switch (Number(value)) {
                //             case 0:
                //                 return '暂存';
                //             case 1:
                //                 return '<span style="color: green;">扣款成功</span>';
                //             case 2:
                //                 return '<span style="color: red;" title="'+row.syncDeductionMessage+'">扣款失败</span>';
                //             case 3:
                //                 return '<span style="color: blue;">无需扣款</span>';
                //             default:
                //                 return '';
                //         }
                //     }
                // },
            ]
        ],
        columns: [
            [
                {
                    field: 'invoiceApplyNo',
                    title: '开票申请单号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'accountStatementNo',
                    title: '对账单号',
                    width: 140,
                    sortable: true
                },{
                field: 'accountStatementYear',
                title: '对账单年份',
                width: 100,
                sortable: true
            },
                {
                    field: 'accountStatementMonth',
                    title: '对账单月份',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'paymentExpireDate',
                    title: '付款到期日',
                    width: 120,
                    sortable: true,
                    exportDateFormatter:'date',
                    formatter: function (value, row) {
                        if (!value) {
                            return '';
                        }
                        return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                    }
                },
                // {
                //     field: 'newPaymentExpireDate',
                //     title: '新付款到期日',
                //     width: 120,
                //     sortable: true,
                //     exportDateFormatter:'date',
                //     formatter: function (value, row) {
                //         if (!value) {
                //             return '';
                //         }
                //         return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                //     }
                // },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 100,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                    }
                },
                {
                    field: 'financeConfirmUserName',
                    title: '财务复核人',
                    width: 100
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270,
                    sortable: true
                },
                {
                    field: 'invoiceNo',
                    title: '到票发票号',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return '<span style="width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; word-break: keep-all;" title="'+ value +'">' + value + '</span>';
                    }
                },
                {
                    field: 'invoiceNetAmount',
                    title: '到票净价总金额',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return 0;
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'invoiceTaxAmount',
                    title: '到票含税总金额',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return 0;
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'invoiceDiffAmount',
                    title: '到票税额',
                    width: 90,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return 0;
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'currencyCode',
                    title: '货币代码',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'companyCode',
                    title: '采购公司',
                    width: 240,
                    sortable: true,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    field: 'invoiceVoucher',
                    title: 'SAP发票凭证号',
                    width: 120,
                    sortable: true
                },
                {
                    field: 'voucherYear',
                    title: '发票年度',
                    width: 100,
                    sortable: true
                },
                // {
                //     field: 'accountantVoucher',
                //     title: '会计凭证',
                //     width: 120,
                //     sortable: true
                // },
                {
                    field: 'invoicePostDate',
                    title: '过账时间',
                    width: 120,
                    sortable: true,
                    exportDateFormatter:'date',
                    formatter: function (value, row) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD');
                    }
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 130,
                    sortable: true,
                    exportDateFormatter:'dateTime',
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'updateTime',
                    title: '最后更新时间',
                    width: 140,
                    sortable: true,
                    exportDateFormatter:'dateTime',
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                // {
                //     field: 'purchaseUser',
                //     title: '采购员',
                //     width: 140,
                // }
                {
                    field: 'createUserName',
                    title: '创建人',
                    width: 140,
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    // lookOrder();
                    detail(2);
                }
            },
            '-',
            {
                text: '财务确认',
                iconCls: 'icon-ok',
                id: 'btn_finance_confirm',
                handler: function () {
                    // optConfirm();
                    detail(4);
                }
            },
            '-',
            {
                text: '财务过账',
                iconCls: 'icon-ok',
                id: 'btn_fin_post',
                handler: function () {
                    // $(el.finPostDialog).dialog('open');
                    // financePost(0);
                    financePostDialog();
                }
            },'-',
            // {
            //     text: '冲账',
            //     iconCls: 'icon-ok',
            //     id: 'btn_fin_post',
            //     handler: function () {
            //         strikePost();
            //     }
            // },'-',
            // {
            //     text: '扣款',
            //     iconCls: 'icon-ok',
            //     id: 'btn_deduction_post',
            //     handler: function () {
            //         deductionPost();
            //     }
            // },'-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_fin_remove',
                handler: function () {
                    delInvoicedApplyOrder();
                }
            },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportInvoiceApply();
            //     }
            // },
            // '-',
            // {
            //     text: '导出Excel',
            //     iconCls: 'icon-download',
            //     id: 'btn_list_export',
            //     handler: function () {
            //         var queryParams = $(el.tb).datagrid('options').queryParams;
            //         queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
            //         queryParams.invoiceVoucher = $.trim($(el.invoiceVoucher).val());
            //         queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
            //         // queryParams.oaProcessNo = $.trim($(el.oaProcessNo).val());
            //         queryParams.companyCode = $(el.companyCode).combobox('getValue');
            //         queryParams.status = $(el.status).combobox('getValue');
            //         queryParams.postStatus = $(el.postStatus).combobox('getValue');
            //         queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
            //         // queryParams.orderType = $(el.orderType).combobox('getValue');
            //         queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
            //         queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
            //         // queryParams.purchaseUser = $('#purchaseUser').textbox('getValue');
            //         queryParams.createUserName = $('#createUserName').textbox('getValue');
            //         queryParams.roleType = 2;
            //         openExportDialog('pc/finance/invoiced/apply/rest/export','tb',queryParams);
            //         exportInvoiceApplyList();
            //     }
            // },
            // {
            //     text: '打印',
            //     iconCls: 'icon-download',
            //     id: 'btn_print_download',
            //     handler: function () {
            //         printInvoice();
            //     }
            // },
            {
                text: '取消确认',
                iconCls: 'icon-redo',
                id: 'btn_finance_confirm_cancel',
                handler: function () {
                    optConfirmCancel();
                }
            }
            // {
            //     text: '修改过账状态',
            //     iconCls: 'icon-redo',
            //     id: 'btn_finance_update_post_status',
            //     handler: function () {
            //         financeDateDialog();
            //     }
            // }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('cost_invoiced_apply_finance_list');
            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (index, row) {
            // 开票申请单状态 7:待财务确认发票 9:发票已确认
            var status = row.status;
            // 按钮 0:查看 1:采购确认 2:财务过账 3:导出
            var btn = $('div.datagrid-toolbar a');
            debugger
            switch (Number(status)){
                case 7:
                    $(el.btn_finance_confirm).linkbutton('enable');
                    $(el.btn_fin_post).linkbutton('disable');
                    // btn.eq(1).linkbutton('enable');
                    // btn.eq(2).linkbutton('disable');
                    break;
                case 9:
                    $(el.btn_finance_confirm).linkbutton('disable');
                    $(el.btn_fin_post).linkbutton('enable');
                    $(el.btn_fin_remove).linkbutton('enable');
                    // btn.eq(1).linkbutton('disable');
                    // btn.eq(2).linkbutton('enable');
                    // btn.eq(3).linkbutton('enable');
                    break;
                default:
                    $(el.btn_finance_confirm).linkbutton('disable');
                    $(el.btn_fin_post).linkbutton('disable');
                    // btn.eq(1).linkbutton('disable');
                    // btn.eq(2).linkbutton('disable');
                    break;
            }
            // 过账状态 1:暂存 2:待预制 3:预制失败 4:预制成功 5:过账成功 6:无需过账 7:已冲销
            if (row.postStatus===5||row.postStatus===4||row.postStatus===6){
                $(el.btn_fin_post).linkbutton('disable');
                if (row.strikeStatus===0||row.strikeStatus===2){
                    btn.eq(3).linkbutton('enable');
                }else {
                    btn.eq(3).linkbutton('disable');
                }
                if (row.deductionStatus===0||row.deductionStatus===2){
                    btn.eq(4).linkbutton('enable');
                }else {
                    btn.eq(4).linkbutton('disable');
                }
            }else {
                btn.eq(2).linkbutton('enable');
                btn.eq(3).linkbutton('disable');
            }

            if (row.postStatus===1||row.postStatus===2||row.postStatus===3||row.postStatus===6||row.postStatus===7){
                $(el.btn_finance_confirm_cancel).linkbutton('enable');
            }else {
                $(el.btn_finance_confirm_cancel).linkbutton('disable');
            }
        },
        // onClickRow: function (index, row) {
        //     // 开票申请单状态 2:待采购确认发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 8:财务驳回发票
        //     var status = row.status;
        //     // 按钮 0:查看 1:采购确认 2:推送OA审批 3:导出
        //     var btn = $('div.datagrid-toolbar a');
        //     switch (Number(status)){
        //         case 7:
        //             btn.eq(1).linkbutton('enable');
        //             btn.eq(2).linkbutton('disable');
        //             break;
        //         case 9:
        //             btn.eq(1).linkbutton('disable');
        //             btn.eq(2).linkbutton('enable');
        //             btn.eq(3).linkbutton('enable');
        //             break;
        //         default:
        //             btn.eq(1).linkbutton('disable');
        //             btn.eq(2).linkbutton('disable');
        //             break;
        //     }
        //     if (row.postStatus===5||row.postStatus===4||row.postStatus===6){
        //         btn.eq(2).linkbutton('disable');
        //         if (row.strikeStatus===0||row.strikeStatus===2){
        //             btn.eq(3).linkbutton('enable');
        //         }else {
        //             btn.eq(3).linkbutton('disable');
        //         }
        //         if (row.deductionStatus===0||row.deductionStatus===2){
        //             btn.eq(4).linkbutton('enable');
        //         }else {
        //             btn.eq(4).linkbutton('disable');
        //         }
        //     }else {
        //         btn.eq(2).linkbutton('enable');
        //         btn.eq(3).linkbutton('disable');
        //     }
        // }
    });
}
//打印
function printInvoice() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert("请选择数据", {icon: 0});
        return false;
    }
    if(row.deleteFlag === 1){ layer.msg("删除的单据不可打印"); return; }

    var companyCode = $(el.companyCode).combobox('getValue');
    if (!companyCode) {
        topWin.layer.alert("请选择采购公司", {icon: 0});
        return false;
    }

    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/finance/invoiced/apply/print2?id=' + row.id + '&companyCode=' + companyCode,
        success: function (data) {
            $('#printOrder').print({
                globalStyles: false,
                mediaPrint: true,
                iframe: true,
                prepend: data,
                deferred: $.Deferred().done(function () {
                    $.ajax({
                        type: 'POST',
                        url: g.ctx + 'pc/finance/invoiced/apply/rest/update/print?id=' + row.id,
                        success: function (data) {
                            $('#tb').datagrid('reload');
                        }
                    });
                })
            });
        }
    });
}

function financePostDialog(){
    var row = $(el.tb).datagrid('getSelections');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    var ids = [];
    for(var i = 0; i < row.length; i++) {
        ids.push(row[i].id); // 假设每行数据都有一个 'id' 字段
    }
    console.log(ids);

    var id = row.id;
    console.log("11111"+id);
    var url = g.ctx + 'pc/finance/cost/invoiced/apply/financePost?id='+ids;
    el.financePostDialog = openDialog('financePostDialog', url, {
        title: '预制发票',
        width: '500',
        height: '450',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.financePostDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '过账',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['financePostDialog'].confirm(function (param) {
                        financePost(param.ids,param.invoicePostDate,param.statementType)
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.financePostDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 冲账
 * @returns {boolean}
 */
function strikePost() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    //预制失败 预制成功 过账成功
    // if (Number(row.postStatus) === 3 || Number(row.postStatus) === 4 || Number(row.postStatus) === 5) {
    if (Number(row.postStatus) !== 5) {
        topWin.layer.alert('开票申请单号: ' + row.invoiceApplyNo + ', 不可以冲账', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要对选中的开票申请单冲账吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'fin/invoiced/apply/rest/strikePost',
            type: 'POST',
            data: {id: row.id},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('冲账成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}

/**
 * 扣款
 * @returns {boolean}
 */
function deductionPost() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    //预制失败 预制成功 过账成功
    // if (Number(row.postStatus) === 3 || Number(row.postStatus) === 4 || Number(row.postStatus) === 5) {
    if (Number(row.postStatus) !== 5) {
        topWin.layer.alert('开票申请单号: ' + row.invoiceApplyNo + ', 不可以扣款', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要对选中的开票申请单扣款吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'fin/invoiced/apply/rest/deductionPost',
            type: 'POST',
            data: {id: row.id},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('扣款成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}
/**
 * 删除开票申请单
 */
function delInvoicedApplyOrder() {
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    //预制失败 预制成功 过账成功
    // if (Number(row.postStatus) === 3 || Number(row.postStatus) === 4 || Number(row.postStatus) === 5) {
    if (Number(row.postStatus) === 2) {
        ids.push(row.id);
    } else {
        topWin.layer.alert('开票申请单号: ' + row.invoiceApplyNo + ', 不可以预制删除', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要删除选中的开票申请单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/del',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('删除成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function optConfirmCancel() {
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    //2:待预制 3:预制失败 7:已冲销
    // if (Number(row.postStatus) === 3 || Number(row.postStatus) === 4 || Number(row.postStatus) === 5) {
    if ((Number(row.postStatus) === 2 || Number(row.postStatus) === 3) || Number(row.postStatus) === 7) {
        ids.push(row.id);
    } else {
        topWin.layer.alert('开票申请单号: ' + row.invoiceApplyNo + ', 不可以取消', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要取消选中的开票申请单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/approve/confirmCancel',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('取消成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}


function updatePostStatus() {
    debugger;
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要修改选中的开票申请单过账状态吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/invoiced/apply/rest/approve/updatePostStatus',
            type: 'POST',
            data: {iaId: row.id,status:5},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('修改成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function financeDateDialog(){
    var row = $(el.tb).datagrid('getSelections');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    var ids = [];
    for(var i = 0; i < row.length; i++) {
        ids.push(row[i].id);
    }
    console.log(ids);

    var id = row.id;
    var url = g.ctx + 'pc/finance/invoiced/apply/financeDate?id='+ids;
    el.financeDateDialog = openDialog('financeDateDialog', url, {
        title: '修改过账状态',
        width: '500',
        height: '450',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.financeDateDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['financeDateDialog'].confirm(function (param) {
                        financeDate(param.ids,param.paymentExpireDate)
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.financeDateDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 查看开票申请单
 */
function lookOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/finance/invoiced/apply/look?id=' + row.id;
    el.lookDialog = openDialog('lookStatementOrder', 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');
                }
            }
        ]
    });
}


/**
 * 财务操作确认
 */
function optConfirm() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    var status = row.status, id = row.id;
    var url = g.ctx + 'pc/finance/invoiced/apply/opt/confirm?id=' + id + '&roleType=2';
    // 数据状态 1:暂存 2:待采购确认 3:采购拒绝 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认 8:财务拒绝 9:确认完成
    if(Number(status) === 7){
        el.optConfirmDialog = openDialog('optConfirm', url, {
            title: '财务确认开票申请单',
            width: '99%',
            height: '100%',
            cache: false,
            modal: true,
            border: 'thin',
            onClose: function () {
                el.optConfirmDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: '通过',
                    iconCls: 'icon-ok',
                    handler: function () {
                        topWin.frames['optConfirm'].dataSave(function (dataParams) {
                            approveConfirm(dataParams, 1);
                        });
                    }
                },
                {
                    text: '拒绝',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        topWin.frames['optConfirm'].dataSave(function (dataParams) {
                            topWin.layer.confirm('您确定要拒绝该开票申请吗?', {icon: 3}, function (index) {
                                topWin.layer.close(index);
                                approveConfirm(dataParams, 0);
                            });
                        });
                    }
                },
                {
                    text: '关闭',
                    iconCls: 'icon-clear',
                    handler: function () {
                        el.optConfirmDialog.dialog('close');
                    }
                }
            ]
        });
    }else {
        topWin.layer.alert('财务只能操作待财务确认状态的开票申请单', {icon: 0});
        return false;
    }
}


/**
 * 财务确认
 *
 * @param dataParams 提交数据
 * @param approveStatus 0:拒绝 1:通过
 */
function approveConfirm(dataParams, approveStatus) {
    dataParams.roleType = 2;
    dataParams.approveStatus = approveStatus;

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/invoiced/apply/rest/approve/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (res) {
            topWin.layer.close(loading);
            el.optConfirmDialog.dialog('close');
            $(el.tb).datagrid('reload');
            topWin.layer.msg('操作成功', {icon: 1});
            // if(Number(approveStatus) === 1){
            //     // 打开过账操作
            //     // financePost(res.id);
            // }else {
            //     topWin.layer.msg('操作成功', {icon: 1});
            // }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 财务预制
 *
 * @param iaId 开票申请单ID
 * @param invoicePostDate 过账时间
 */
function financePost(iaId,invoicePostDate,statementType) {
    let ids = [];
    if(Number(iaId) === 0){
        // var row = $(el.tb).datagrid('getSelected');
        // if (!row) {
        //     topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        //     return false;
        // }
        // // 数据状态 1:暂存 2:待采购确认 3:采购拒绝 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认 8:财务拒绝 9:确认完成
        // // 过账状态 1:暂存 2:待过账 3:过账失败 4:过账成功
        // if(Number(row.status) !== 9 || (Number(row.postStatus) !== 2 && Number(row.postStatus) !== 3 && Number(row.postStatus) !== 4)){
        //     topWin.layer.alert('只有财务确认完成状态的开票申请单才能进行预制操作', {icon: 0});
        //     return false;
        // }

        // iaId = row.id;
        var rows = $(el.tb).datagrid('getSelections');
        if (!rows || rows.length <= 0) {
            topWin.layer.alert('请选中一条记录', {icon: 0});
            return false;
        }
        let financeConfirmUserName = "";

        // for (let i = 0; i < rows.length; i++) {
        //     ids.push(rows[i].id);
        //     if (i === 0) {
        //         financeConfirmUserName = rows[i].financeConfirmUserName;
        //         continue;
        //     }
        //     if (rows[i].purchaseGroupCode !== financeConfirmUserName) {
        //         topWin.layer.msg("所选财务复核人必须一致");
        //         return false;
        //     }
        // }
    }
    //iaId.join(",");
    var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16,time: 100000,shade : [0.5 , '#000' , true]});
    //预制发票
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/cost/invoiced/apply/detail/rest/create/prefabricate/invoice',
        data: {iaIds:iaId,type:1,invoicePostDate:invoicePostDate,statementType:statementType},
        success: function (data) {
            topWin.layer.close(loading);
            $(el.tb).datagrid('reload');
            topWin.layer.msg("预制成功");
            closeSyncDialog();
        },
        error:function (data) {
            topWin.layer.close(loading);
            $(el.tb).datagrid('reload');
            closeSyncDialog();
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


function financeDate(iaId,paymentExpireDate) {
    let ids = [];
    if(Number(iaId) === 0){

        var rows = $(el.tb).datagrid('getSelections');
        if (!rows || rows.length <= 0) {
            topWin.layer.alert('请选中一条记录', {icon: 0});
            return false;
        }

    }
    var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16,time: 100000,shade : [0.5 , '#000' , true]});
    //付款到期日
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/invoiced/apply/rest/approve/updatePostStatus',
        data: {iaId:iaId,type:5,paymentExpireDate:paymentExpireDate},
        success: function (data) {
            topWin.layer.close(loading);
            $(el.tb).datagrid('reload');
            topWin.layer.msg("更新付款到期日成功");
            el.financeDateDialog.dialog('close');

            closeSyncDialog();
        },
        error:function (data) {
            topWin.layer.close(loading);
            $(el.tb).datagrid('reload');
            el.financeDateDialog.dialog('close');
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 确定过账
 */
function confirmSync() {
    var invoicePostDate = $(el.invoicePostDate).datebox('getValue');
    var statementType = $(el.statementType).combobox('getValue');
    var ids = $(el.iaId).combobox('getValue');
    if(!invoicePostDate){
        topWin.layer.alert('请填写发票过账日期', {icon: 0});
        return false;
    }
    financePost(ids,invoicePostDate,statementType)
}


/**
 * 关闭发票过账数据输入弹框
 */
function closeSyncDialog() {
    el.financePostDialog.dialog('close');
}


/**
 * 导出开票申请
 */
function exportInvoiceApply() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'pc/finance/invoiced/apply/rest/data/export?id=' + row.id;
    window.open(url);
}

function exportInvoiceApplyList() {
    topWin.layer.confirm('您确定要导出数据?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        var query = {};
        query.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
        query.invoiceVoucher = $.trim($(el.invoiceVoucher).val());
        query.supCodeOrName = $.trim($(el.supCodeOrName).val());
        query.companyCode = $(el.companyCode).combobox('getValue');
        query.status = $(el.status).combobox('getValue');
        query.postStatus = $(el.postStatus).combobox('getValue');
        query.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
        query.createTimeStart = $(el.createTimeStart).datebox('getValue');
        query.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
        query.createUserName = $('#createUserName').textbox('getValue');
        query.roleType = 2;
        var url = g.ctx + 'fin/invoiced/apply/rest/exportList' +
            '?invoiceApplyNo=' + query.invoiceApplyNo +
            '&invoiceVoucher=' + query.invoiceVoucher +
            '&supCodeOrName=' + query.supCodeOrName +
            '&companyCode=' + query.companyCode +
            '&status=' + query.status +
            '&postStatus=' + query.postStatus +
            '&purchaseGroup=' + query.purchaseGroup +
            '&createTimeStart=' + query.createTimeStart +
            '&createTimeEnd=' + query.createTimeEnd +
            '&createUserName=' + query.createUserName +
            '&roleType=' + query.roleType;
        window.open(encodeURI(url));
    });
}


/**
 * 查询对账单数据
 */
function searchIaData() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
    queryParams.invoiceVoucher = $.trim($(el.invoiceVoucher).val());
    queryParams.financeConfirmUserName = $.trim($(el.financeConfirmUserName).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    // queryParams.oaProcessNo = $.trim($(el.oaProcessNo).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.postStatus = $(el.postStatus).combobox('getValue');
    queryParams.currencyCode = $(el.currencyCode).combobox('getValue');
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.paperlessFlag = $(el.paperlessFlag).combobox('getValue');
    // queryParams.orderType = $(el.orderType).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.paymentExpireDateStart = $(el.paymentExpireDateStart).datebox('getValue');
    queryParams.paymentExpireDateEnd = $(el.paymentExpireDateEnd).datebox('getValue');
    // queryParams.purchaseUser = $('#purchaseUser').textbox('getValue');
    queryParams.createUserName = $('#createUserName').textbox('getValue');
    queryParams.roleType = 2;
    queryParams.accountStatementMonth = $(el.accountStatementMonth).val();
    queryParams.accountStatementYear = $(el.accountStatementYear).val();
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetIaSearch() {
    $(el.supCodeOrName).val('');
    // $(el.oaProcessNo).val('');
    $(el.invoiceApplyNo).val('');
    $(el.invoiceVoucher).val('');
    $(el.financeConfirmUserName).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.purchaseGroup).combobox('setValue', '');
    $(el.paperlessFlag).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.postStatus).combobox('setValue', -1);
    $(el.currencyCode).combobox('setValue', '');
    // $(el.orderType).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $(el.paymentExpireDateStart).datebox('setValue', '');
    $(el.paymentExpireDateEnd).datebox('setValue', '');
    $(el.createUserName).textbox('setValue', '');
    $('#purchaseUser').textbox('setValue', '');
    $(el.accountStatementYear).val('');
    $(el.accountStatementMonth).combobox('setValue', "");
    searchIaData();
}


/**
 * 查看OA审批日志
 *
 * @param ele 当前操作DOM节点
 */
function lookOaApproveLog(ele) {
    var url = g.ctx + 'fin/common/look/oa/log/dialog?oaProcessNo=' + $(ele).data('op');
    var lookOaLogDialog = openDialog('lookOaLogDialog', url, {
        title: '查看OA审批日志',
        width: '55%',
        height: '50%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            lookOaLogDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    lookOaLogDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 查看开票申请过账结果
 *
 * @param ele 当前操作DOM节点
 */
function lookPostResult(ele) {
    openPostResultDialog($(ele).data('id'));
}


/**
 *
 *
 * @param iaId
 */
function openPostResultDialog(iaId) {
    var url = g.ctx + 'fin/common/look/post/result/dialog?iaId=' + iaId;
    var lookPostResultDialog = openDialog('lookPostResultDialog', url, {
        title: '查看开票申请过账结果',
        width: '55%',
        height: '400px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            lookPostResultDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    lookPostResultDialog.dialog('close');
                }
            }
        ]
    });
}