/**
 * 对账模块-材料开票申请管理首页
 *
 * Created by li.kui on 2020/8/20.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    orderType: '#orderType',
    searchForm: '#searchForm',
    companyCode: '#companyCode',
    supCodeOrName: '#supCodeOrName',
    invoiceApplyNo: '#invoiceApplyNo',
    invoiceVoucher: '#invoiceVoucher',
    invoiceNumber: '#invoiceNumber',
    invoiceDateStart:'#invoiceDateStart',
    invoiceDateEnd:'#invoiceDateEnd',
    oaProcessNo: '#oaProcessNo',
    supplierCode: '#supplierCode',
    status: '#status',
    postStatus: '#postStatus',
    tb: '#tb',
    mvPostDateStart: '#mvPostDateStart',
    mvPostDateEnd: '#mvPostDateEnd',
    note: '#note',
    financeConfirmUserName: '#financeConfirmUserName',
    deductionStatus:'#deductionStatus',
    addOrEditDialog: null,
    optConfirmDialog: null,
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


$(function () {
    // 初始化公司名称下拉框
    $(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());
        // }
    });
    loadGrid();
});


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

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        // url: g.ctx + 'fin/invoiced/receipt/rest/find/by/apply/id',
        url: g.ctx + 'pc/finance/invoiced/receipt/rest/list',
        height: el.bodyHeight - searchHeight,
        // singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        // page: 1,
        // pageSize: 20,
        queryParams: {

        },
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                // {
                //     field: 'deleteFlag',
                //     title: '数据状态',
                //     width: 90,
                //     sortable: true,
                //     exportEnum:[
                //         {code:0,codeWithDesc:'正常'},
                //         {code:1,codeWithDesc:'已冲销'}
                //     ],
                //     formatter: function (value) {
                //         if (Number(value)===0){
                //             return '<span style="color: green;">正常</span>';
                //         }else if (Number(value)===1){
                //             return '<span style="color: red;">已冲销</span>';
                //         }
                //     },
                // },
                {
                    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: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 200,
                    sortable: true
                },
                {
                    field: 'invoiceApplyNo',
                    title: '开票申请单号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'accountStatementNo',
                    title: '对账单号',
                    width: 140
                },
                {
                    field: 'invoiceVoucher',
                    title: 'SAP发票凭证号',
                    width: 120,
                    sortable: true
                },
                {
                    field: 'voucherYear',
                    title: '发票年度',
                    width: 100,
                    sortable: true
                },
                // {
                //     field: 'accountantVoucher',
                //     title: '会计凭证',
                //     width: 120,
                //     sortable: true
                // },
                {
                    field: 'deductionStatus',
                    title: '抵扣状态',
                    width: 120,
                    sortable: true,
                    exportEnum:[
                        {code:1,codeWithDesc:'待认证'},
                        {code:2,codeWithDesc:'已认证'},
                        {code:3,codeWithDesc:'红冲'}
                    ],
                    formatter: function (value) {
                        // 数据状态 1:待认证 2:已认证 3:红冲
                        switch (value) {
                            case '1':
                                return '<span style="color: red;">待认证</span>';
                            case '2':
                                return '<span style="color: green;">已认证</span>';
                            case '3':
                                return '红冲';
                            default:
                                return '';
                        }
                    },
                },
                {
                    field: 'note',
                    title: '备注',
                    width: 150,
                    sortable: true
                },
                {
                    field: 'financeConfirmUserName',
                    title: '财务复核人',
                    width: 100
                },
                {
                    field: 'deductionCodeType',
                    title: '可抵扣编号',
                    width: 100,
                    exportEnum:[
                        {code:1,codeWithDesc:'可抵扣'},
                        {code:2,codeWithDesc:'不可抵扣'}
                    ],
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '可抵扣';
                        }
                        if (Number(value) === 2) {
                            return '不可抵扣';
                        }
                        else {
                            return '';
                        }
                    },
                },
                {
                    field: 'invoiceDate',
                    title: '发票日期',
                    width: 180,
                    exportDateFormatter:'date',
                    sortable: true,
                    formatter: function (value) {
                        if (value){
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    },
                },
                {
                    field: 'invoiceCode',
                    title: '发票代码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },

                {
                    field: 'invoiceNumber',
                    title: '发票号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'electronInvoiceNumber',
                    title: '数电发票号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                // {
                //     field: 'dutyParagraph',
                //     title: '税号',
                //     width: 150,
                //     editor: {
                //         type: 'textbox'
                //     }
                // },
                {
                    field: 'taxRate',
                    title: '税率',
                    width: 170,
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 120,
                },
                {
                    field: 'taxAmount',
                    title: '含税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'noTaxAmount',
                    title: '未税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'diffTaxMoney',
                    title: '税额',
                    width: 130,
                    formatter: function (value, row) {
                        if (row.taxAmount && row.noTaxAmount) {
                            return new BigNumber(row.taxAmount - row.noTaxAmount).toFixed(2);
                        }
                        return 0
                    },
                },
                {
                    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: 'invoicePostDate',
                    title: '过账时间',
                    width: 130,
                    sortable: true,
                    exportDateFormatter:'dateTime',
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'fileId',
                    title: '发票附件',
                    width: 200,
                    exportHidden:true,
                    formatter: function (value, row, index) {
                        if (!value){
                            return '';
                        }
                        return "<a style=\"color: #108ee9\" href='" + g.ctx + "pc/sys/file/rest/download/" + value + "'>下载</a>";
                        // return '<a style="color: #108ee9" onclick="replyDownload(' + value + ')">下载</a>';
                    },
                }
            ]
        ],
        toolbar: [
            {
                text: '导出Excel',
                // id:'icon_download',
                id:"icon_download",
                iconCls: 'icon-download',
                handler: function () {
                    var queryParams = $(el.tb).datagrid('options').queryParams;
                    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
                    // queryParams.createTimeStart = $.trim($(el.createTimeStart).val());
                    // queryParams.createTimeEnd = $.trim($(el.createTimeEnd).val());
                    queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
                    queryParams.invoiceVoucher = $.trim($(el.invoiceVoucher).val());
                    queryParams.invoiceNumber = $.trim($(el.invoiceNumber).val());
                    queryParams.mvPostDateStart = $(el.mvPostDateStart).datebox('getValue');
                    queryParams.mvPostDateEnd = $(el.mvPostDateEnd).datebox('getValue');
                    queryParams.invoiceDateStart = $(el.invoiceDateStart).datebox('getValue');
                    queryParams.invoiceDateEnd = $(el.invoiceDateEnd).datebox('getValue');
                    openExportDialog('pc/finance/invoiced/receipt/rest/export','tb',queryParams);
                    setOperationLog("导出Excel按钮", "发票名称");

                }
            },
            // {
            //     text: '文件批量下载',
            //     id: 'btn_batch_download',
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         var rows = $(el.tb).datagrid("getChecked");
            //         if (rows.length <= 0) {
            //             layer.confirm("请选择至少一条数据");
            //             return
            //         }
            //         var ids = [];
            //         $.each(rows, function (idx, itm) {
            //             if(itm.fileId){
            //             ids.push(itm.fileId);
            //             }
            //         });
            //         uploadFileUIopen(ids.join(','), 1);
            //     }
            // },
            {
                text: '抵扣处理',
                id: 'deduction_handle',
                iconCls: 'icon-edit',
                handler: function () {
                    deductionHandle();
                }
                // handler: function () {
                //     var rows = $(el.tb).datagrid("getChecked");
                //     if (rows.length <= 0) {
                //         layer.confirm("请选择至少一条数据");
                //         return
                //     }
                //     var deStatus = [];
                //     var notes = [];
                //     $.each(rows, function (idx, itm) {
                //         if(itm.deductionStatus){
                //             deStatus.push(itm.deductionStatus);
                //         }
                //     });
                //     $.each(rows, function (idx, itm) {
                //         if(itm.note){
                //             notes.push(itm.note);
                //         }
                //     });
                //     deductionStatusChange()
                // }
            }

        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('finance.receive.invoiceDetail');
            $(el.tb).datagrid('clearSelections');
        }
    });
}

function deductionHandle(){
    var rows = $(el.tb).datagrid('getChecked');
    if (rows.length <= 0) {
        layer.msg("请选择需要修改的数据");
        return;
    }

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

    // var ids = [];
    // $.each(rows, function (idx, itm) {
    //     ids.push(itm.id);
    // })
    var updateDeductionStatusDialog = openDialog("updateDeductionStatusDialog", g.ctx+"pc/finance/invoice/detail/updateDeductionStatusPage?ids=" + ids.join(","), {
        title: '抵扣处理',
        width: '800px',
        height: '520px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            updateDeductionStatusDialog.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['updateDeductionStatusDialog'].page.save(() => {
                    updateDeductionStatusDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });

            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                updateDeductionStatusDialog.dialog('close');
            }
        }]
    });
}

function replyDownload(fileId){
    window.location.href = g.ctx+'pc/sys/file/rest/download/'+fileId;
}
function previewPDFNew(fileId,fileName){
    localStorage.pdf_url = 'pc/file/rest//download/'+fileId;
    openMainLayerWin("PDF文件预览",'/static/pdfjs1/web/viewer.html',"1000px;","100%");
}
function uploadFileUIopen(value, batchDownload) {
    var url = g.ctx + 'xj/common/file/upload/page?value=' + value + '&businessType=7&batchDownload=' + batchDownload;
    openLayerWin('文件批量下载', url, '800px', '600px');
}
function previewImg(fileId,fileName){
    layer.photos({
        photos: {
            "title": "图片预览",
            "start": 0,
            "data": [
                {
                    "alt": fileName,
                    "pid": 5,
                    "src": 'pc/file/rest//download/'+fileId
                }
            ]
        }
    });
}


/**
 * 查询对账单数据
 */
function searchIaData() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    // queryParams.createTimeStart = $.trim($(el.createTimeStart).val());
    // queryParams.createTimeEnd = $.trim($(el.createTimeEnd).val());
    queryParams.invoiceApplyNo = $.trim($(el.invoiceApplyNo).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.invoiceVoucher = $.trim($(el.invoiceVoucher).val());
    queryParams.invoiceNumber = $.trim($(el.invoiceNumber).val());
    queryParams.note = $.trim($(el.note).val());
    queryParams.financeConfirmUserName = $.trim($(el.financeConfirmUserName).val());
    queryParams.mvPostDateStart = $(el.mvPostDateStart).datebox('getValue');
    queryParams.mvPostDateEnd = $(el.mvPostDateEnd).datebox('getValue');
    queryParams.invoiceDateStart = $(el.invoiceDateStart).datebox('getValue');
    queryParams.invoiceDateEnd = $(el.invoiceDateEnd).datebox('getValue');
    queryParams.deductionStatus = $(el.deductionStatus).combobox('getValue');
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetIaSearch() {
    $(el.supCodeOrName).val('');
    $(el.oaProcessNo).val('');
    $(el.invoiceApplyNo).val('');
    $(el.invoiceNumber).val('');
    $(el.invoiceVoucher).val('');
    $(el.statementNo).val('');
    $(el.financeConfirmUserName).val('');
    $(el.note).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.postStatus).combobox('setValue', -1);
    $(el.invoiceDateStart).datebox('setValue', '');
    $(el.invoiceDateEnd).datebox('setValue', '');
    $('#invoiceTaxMoneyBegin').numberbox('setValue','');
    $('#invoiceTaxMoneyEnd').numberbox('setValue','');
    $('#purchaseUser').textbox('setValue','');
    $(el.mvPostDateStart).datebox('setValue', '');
    $(el.mvPostDateEnd).datebox('setValue', '');
    $(el.deductionStatus).combobox('setValue','');
    searchIaData();
}
