/**
 * 对账模块-材料开票申请管理首页
 *
 * Created by li.kui on 2020/8/20.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    btn_add: '#btn_add',
    btn_edit: '#btn_edit',
    btn_del: '#btn_del',
    btn_submit: '#btn_submit',
    orderType: '#orderType',
    searchForm: '#searchForm',
    companyCode: '#companyCode',
    createUserName: '#createUserName',
    supCodeOrName: '#supCodeOrName',
    invoiceApplyNo: '#invoiceApplyNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    currencyCode: '#currencyCode',
    oaProcessNo: '#oaProcessNo',
    purchaseGroup: '#purchaseGroup',
    paperlessFlag: '#paperlessFlag',
    status: '#status',
    postStatus: '#postStatus',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    tb: '#tb',
    addOrEditDialog: null,
    optConfirmDialog: null,
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


$(function () {
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/company/rest/listAll')
    initComBoBoxData();

    loadGrid();
});


/**
 * 初始化页面下拉框数据
 */
function initComBoBoxData() {
    var isSupplier = $(el.isSupplier).val(), comUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=0';
    if (Number(isSupplier) === 1) {
        comUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=0';
    }

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

    // 初始化过账状态下拉框
    $(el.postStatus).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 过账状态 -1:全部 1:暂存 2:待过账 3:过账失败 4:过账成功
            {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: comUrl,
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });

    //初始化日期
    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'
    });

}


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

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/sup/list?roleType=1',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            orderType: $(el.orderType).val()
        },
        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: rebeccapurple;">待采购确认发票</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: 'isPrint',
                //     title: '是否打印',
                //     width: 80,
                //     sortable: true,
                //     formatter:function (value) {
                //         if(value === 0){
                //             return "未打印"
                //         }else{
                //             return "<span style='color: red;'>已打印</span>"
                //         }
                //     }
                // },
                {
                    field: 'deleteFlag',
                    title: '删除标记',
                    width: 80,
                    sortable: true,
                    exportEnum:[
                        {code:0,codeWithDesc:'未删除'},
                        {code:1,codeWithDesc:'已删除'}
                    ],
                    formatter:function (value,row) {
                        if(value === 0){
                            return "未删除"
                        }else{
                            return '<span style="color: red;" title="'+row.writeOff+'">已删除</span>';
                        }
                    }
                },
                // {
                //     field: 'foreignCurrencyAddFlag',
                //     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: '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:过账成功
                        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: green;">预制成功</span>';
                            case 5:
                                return '<span style="color: blue;" >过账成功</span>';
                            case 6:
                                return '<span style="color: grey;">无需过账</span>';
                            case 7:
                                return '<span  style="color: red;">已冲销</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: 'purchaseGroup',
                    title: '采购组',
                    width: 100,
                    exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                    }
                },
                {
                    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,
                    exportEnum:getNecessaryDataList('pc/sys/company/rest/listAll'),
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    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,
                },
                {
                    field: 'writeOff',
                    title: '冲销原因',
                    width: 140,
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    // lookOrder();
                    detail(2)
                }
            },
            '-',
            {
                text: '发票资料交接',
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    // addInvoicedApplyOrder();
                    detail(0)
                }
            },
            '-',
            {
                text: '无发票资料交接',
                iconCls: 'icon-add',
                id: 'btn_not_cny_add',
                handler: function () {
                    if (Number(supplierCnyFlag)===1){
                        topWin.layer.alert("当前供应商用户币种为CNY，不可操作", {icon: 0});
                        return false;
                    }
                    detail(5)
                }
            },
            '-',
            {
                text: '编辑',
                iconCls: 'icon-edit',
                id: 'btn_edit',
                handler: function () {
                    // editInvoicedApplyOrder();
                    detail(1)
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_del',
                handler: function () {
                    delInvoicedApplyOrder();
                }
            },
            '-',
            {
                text: '提交确认',
                iconCls: 'icon-ok',
                id: 'btn_submit',
                handler: function () {
                    submitConfirm();
                }
            },
            '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-redo',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportInvoiceApply();
            //     }
            // }, '-',
            // {
            //     text: '打印',
            //     iconCls: 'icon-download',
            //     id: 'btn_print_download',
            //     handler: function () {
            //         printInvoice();
            //     }
            // },
            '-',
            {
                text: '列表导出',
                iconCls: 'icon-redo',
                id: 'btn_list_export',
                handler: function () {
                    openExportDialog('pc/finance/cost/invoiced/apply/rest/sup/export','tb', getQuery());
                }
            }, "-",
            {
                text: '冲销原因',
                iconCls: 'icon-remove',
                id: 'btn_writeOff',
                handler: function () {
                    writeOff();
                }
            },
            '-',
            {
                text: '推送影像',
                iconCls: 'icon-ok',
                id: 'btn_to_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                    $.ajax({
                        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/toImg',
                        type: 'POST',
                        data: {
                            iaId: row.id
                        },
                        success: function () {
                            topWin.layer.close(loading);
                            topWin.layer.msg('推送成功', {icon: 1});
                            $(el.tb).edatagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.close(loading);
                            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            '-',
            {
                text: '删除影像',
                iconCls: 'icon-delete',
                id: 'btn_delete_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    var loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                    $.ajax({
                        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/deleteImg',
                        type: 'POST',
                        data: {
                            iaId: row.id
                        },
                        success: function () {
                            topWin.layer.close(loading);
                            topWin.layer.msg('删除成功', {icon: 1});
                            $(el.tb).edatagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.close(loading);
                            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            '-',
            {
                text: '查看影像',
                iconCls: 'icon-find',
                id: 'btn_look_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    const imageCode = row.imgCode;
                    if (!imageCode) {
                        topWin.layer.alert("请先推送影像", {icon: 2, title: "温馨提示"});
                    } else {
                        $.ajax({
                            type: 'get',
                            url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
                            data: {
                                imageCode: imageCode
                            },
                            success: function (data) {
                                if (data) {
                                    window.open(data, "_blank");
                                }
                            },
                            error: function (error) {
                                topWin.layer.alert(error.responseJSON.message, {
                                    icon: 2,
                                    content: error.responseJSON.message
                                });
                            }
                        });
                    }
                }
            },
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('cost_invoiced_apply_list');
            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var status = rows[rowIndex].status;
            // 开票申请单状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
            switch (Number(status)) {
                case 1:
                    $(el.btn_edit).linkbutton('enable');
                    $(el.btn_del).linkbutton('enable');
                    $(el.btn_submit).linkbutton('enable');
                    break;
                case 2:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 3:
                    $(el.btn_edit).linkbutton('enable');
                    $(el.btn_del).linkbutton('enable');
                    $(el.btn_submit).linkbutton('enable');
                    break;
                case 4:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 5:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 6:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 7:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 8:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                case 9:
                    $(el.btn_edit).linkbutton('disable');
                    $(el.btn_del).linkbutton('disable');
                    $(el.btn_submit).linkbutton('disable');
                    break;
                default:
                    break;
            }
        }
    });
}

//冲销原因
function writeOff(){
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    if (Number(row.postStatus) === 7){
        topWin.layer.alert('只有已冲销的数据才能填写冲销原因', {icon: 0});
        return false;
    }
    var id = row.id;
    topWin.layer.prompt({title: "请填写冲销原因", formType: 2, value: '', maxlength: 500}, function(text, index){
        if(text ===''){
            topWin.layer.msg('请填写冲销原因', {icon: 2});
            return;
        }
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/writeOff',
            method: "post",
            data: {id: id,writeOff:text},
            success: function () {
                topWin.layer.close(index);
                topWin.layer.msg('数据保存成功', {icon: 1});
                $(el.tb).datagrid('reload');
                $(el.tb).datagrid('clearSelections');
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}
//打印
function printInvoice() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert("请选择数据", {icon: 0});
        return false;
    }
    if(row.deleteFlag === 1){ layer.msg("删除的单据不可打印"); return; }

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

/**
 * 查看开票申请单
 */
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 addInvoicedApplyOrder() {
    var url = g.ctx + 'pc/finance/invoiced/apply/add?orderType=' + $(el.orderType).val();
    el.addOrEditDialog = openDialog('addInvoicedApply', url, {
        title: '新增开票申请单',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addOrEditDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '暂存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['addInvoicedApply'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.addOrEditDialog.dialog('close');
                    });
                }
            },
            // {
            //     text: '提交',
            //     iconCls: 'icon-ok',
            //     handler: function () {
            //         topWin.frames['addInvoicedApply'].dataSave(function (applyId) {
            //             console.info('数据保存成功');
            //             console.info(applyId);
            //             topWin.layer.msg('数据保存成功', {icon: 1});
            //             $(el.tb).datagrid('load');
            //             el.addOrEditDialog.dialog('close');
            //
            //             dataSaveSubmit(applyId.id);
            //         });
            //     }
            // },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addOrEditDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 编辑开票申请单
 */
function editInvoicedApplyOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    if (Number(row.deleteFlag) !== 0) {
        topWin.layer.alert('该开票申请单已经删除，不可操作', {icon: 0});
        return false;
    }
    if (Number(row.status) === 1 || Number(row.status) === 3) {
        var url = g.ctx + 'pc/finance/invoiced/apply/edit?id=' + row.id;
        el.addOrEditDialog = openDialog('editInvoicedApply', url, {
            title: '编辑开票申请单',
            width: '99%',
            height: '100%',
            cache: false,
            modal: true,
            border: 'thin',
            onClose: function () {
                el.addOrEditDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: '暂存',
                    iconCls: 'icon-save',
                    handler: function () {
                        topWin.frames['editInvoicedApply'].dataSave(function () {
                            topWin.layer.msg('数据保存成功', {icon: 1});
                            $(el.tb).datagrid('load');
                            el.addOrEditDialog.dialog('close');
                        });
                    }
                },
                // {
                //     text: '提交',
                //     iconCls: 'icon-ok',
                //     handler: function () {
                //         topWin.frames['editInvoicedApply'].dataSave(function (applyId) {
                //             topWin.layer.msg('数据保存成功', {icon: 1});
                //             $(el.tb).datagrid('load');
                //             el.addOrEditDialog.dialog('close');
                //
                //             dataSaveSubmit(applyId);
                //         });
                //     }
                // },
                {
                    text: '取消',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        el.addOrEditDialog.dialog('close');
                    }
                }
            ]
        });
    } else {
        topWin.layer.alert('只能编辑暂存或采购拒绝状态的对账单', {icon: 0});
        return false;
    }
}


/**
 * 删除开票申请单
 */
function delInvoicedApplyOrder() {
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    //暂存 采购拒绝 财务拒绝
    if (Number(row.status) === 1 || Number(row.status) === 3 || Number(row.status) === 8) {
        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 submitConfirm() {
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择您需要提交的开票申请单进行操作', {icon: 0});
        return false;
    }
    if (Number(row.status) === 1 || Number(row.status) === 3) {
        ids.push(row.id);
    } else {
        topWin.layer.alert('只有暂存或者采购拒绝的开票申请单才能提交确认', {icon: 0});
        return false;
    }
    if (Number(row.deleteFlag) !== 0) {
        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/cost/invoiced/apply/rest/submit/confirm',
            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: '温馨提示'});
            }
        });
    });
}


/**
 * 数据保存后提交
 *
 * @param applyId 开票申请单ID
 */
function dataSaveSubmit(applyId) {
    var ids = [];
    console.log("applyId: " + applyId);
    ids.push(applyId);

    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/submit/confirm',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                if (0 === Number($(el.isSupplier).val())) {
                    var url = g.ctx + 'fin/invoiced/apply/opt/confirm?id=' + applyId + '&roleType=1';
                    openPurchaseConfirmDialog(url);
                } else {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    $(el.tb).datagrid('load');
                }
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 打开对账单确认页面
 *
 * @param url 页面URL
 */
function openPurchaseConfirmDialog(url) {
    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) {
                        purchaseApprove(dataParams, 1);
                    });
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['optConfirm'].dataSave(function (dataParams) {
                        purchaseApprove(dataParams, 0);
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    el.optConfirmDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 采购审批
 *
 * @param dataParams 提交数据
 * @param approveStatus 0:拒绝 1:通过
 */
function purchaseApprove(dataParams, approveStatus) {
    dataParams.roleType = 1;
    dataParams.approveStatus = approveStatus;
    debugger;
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'fin/invoiced/apply/rest/approve/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            el.optConfirmDialog.dialog('close');
            $(el.tb).datagrid('reload');

            if (Number(data) === 4) {
                topWin.layer.alert('确认数据保存成功, 但推送OA审批失败请尝试手动推送', {icon: 1});
            } else {
                topWin.layer.msg('操作成功', {icon: 1});
            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 导出开票申请
 */
function exportInvoiceApply() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
        return false;
    }
    var url = g.ctx + 'pc/finance/cost/invoiced/apply/rest/data/export?id=' + row.id;
    window.open(url);
}


/**
 * 查询对账单数据
 */
function searchIaData() {
    // var queryParams = $(el.tb).datagrid('options').queryParams;
    // queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
    // queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    // queryParams.oaProcessNo = $.trim($(el.oaProcessNo).val());
    // queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    // queryParams.paperlessFlag = $(el.paperlessFlag).combobox('getValue');
    // queryParams.companyCode = $(el.companyCode).combobox('getValue');
    // queryParams.createUserName = $(el.createUserName).textbox('getValue');
    // queryParams.status = $(el.status).combobox('getValue');
    // queryParams.postStatus = $(el.postStatus).combobox('getValue');
    // queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    // queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    // queryParams.invoiceTaxMoneyBegin = $('#invoiceTaxMoneyBegin').numberbox('getValue');
    // queryParams.invoiceTaxMoneyEnd = $('#invoiceTaxMoneyEnd').numberbox('getValue');
    // // queryParams.purchaseUser = $('#purchaseUser').textbox('getValue');
    // queryParams.currencyCode = $(el.currencyCode).combobox('getValue');
    // $(el.tb).datagrid('load');


    $(el.tb).datagrid('options').queryParams = getQuery();
    $(el.tb).datagrid('load');
}

function getQuery() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.oaProcessNo = $.trim($(el.oaProcessNo).val());
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.paperlessFlag = $(el.paperlessFlag).combobox('getValue');
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.createUserName = $(el.createUserName).textbox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.postStatus = $(el.postStatus).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.invoiceTaxMoneyBegin = $('#invoiceTaxMoneyBegin').numberbox('getValue');
    queryParams.invoiceTaxMoneyEnd = $('#invoiceTaxMoneyEnd').numberbox('getValue');
    // queryParams.purchaseUser = $('#purchaseUser').textbox('getValue');
    queryParams.currencyCode = $(el.currencyCode).combobox('getValue');
    queryParams.accountStatementMonth = $(el.accountStatementMonth).val();
    queryParams.accountStatementYear = $(el.accountStatementYear).val();

    return queryParams;
}
/**
 * 重置查询
 */
function resetIaSearch() {
    $(el.supCodeOrName).val('');
    $(el.oaProcessNo).val('');
    $(el.invoiceApplyNo).val('');
    $(el.statementNo).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.currencyCode).combobox('setValue', '');
    $(el.purchaseGroup).combobox('setValue', '');
    $(el.paperlessFlag).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.postStatus).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $('#invoiceTaxMoneyBegin').numberbox('setValue','');
    $('#invoiceTaxMoneyEnd').numberbox('setValue','');
    $('#purchaseUser').textbox('setValue','');
    $('#createUserName').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) {
    var url = g.ctx + 'fin/common/look/post/result/dialog?iaId=' + $(ele).data('id');
    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');
                }
            }
        ]
    });
}