var el = {
    id:'#id',
    dataDiv: '#dataDiv',
    tbInvoice: '#tbInvoice',
    form: '#form',
    approveRemark: '#approveRemark',
    bodyHeight: document.documentElement.clientHeight
};
var taxDict = [];
$(function () {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                var obj = {};
                obj.id = data[i].id;
                obj.itemCode = data[i].taxCode;
                obj.itemName = data[i].taxName;
                obj.itemValue = data[i].taxValue;
                obj.itemRemark = data[i].taxName;
                taxDict.push(obj);
            }
        }
    });
    initTbInvoice();
});

/**
 * 初始化关联发票表格
 */
function initTbInvoice() {
    var toolbars = [];
    var columns =  [
        [
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'file',
                title: '发票附件',
                width: 230,
                formatter: function (value, row, index) {
                    if (!row.fileId){
                        // return '<a style="color: grey" >点我上传</a>';
                        return '';
                    }
                    return '<div class="invoice-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+row.fileId+'"></div>';
                    // return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                    // return "<a style=\"color: #108ee9\" href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>";
                }
            },
            {
                field: 'type',
                title: '发票类型',
                width: 100,
                sortable: true,
                exportEnum:[
                    {code:0,codeWithDesc:'蓝票'},
                    {code:1,codeWithDesc:'红票'},
                ],
                formatter: function (value) {
                    switch (Number(value)) {
                        case 0:
                            return '<span style="color: blue;">蓝票</span>';
                        case 1:
                            return '<span style="color: red;">红票</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'deductionStatus',
                title: '发票状态',
                width: 100,
                sortable: true,
                exportEnum:[
                    {code:3,codeWithDesc:'红冲'},
                ],
                formatter: function (value) {
                    switch (Number(value)) {
                        case 3:
                            return '<span style="color: red;">红冲</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'deductionCodeType',
                title: '可抵扣编号',
                width: 80,
                formatter: function (value) {
                    if (Number(value) === 1) {
                        return '可抵扣';
                    }
                    if (Number(value) === 2) {
                        return '不可抵扣';
                    }
                }
            },
            {
                field: 'invoiceDate',
                title: '发票日期',
                width: 80,
                formatter: function (value) {
                    if (value){
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return '';
                }
            },
            {
                field: 'invoiceCode',
                title: '发票代码',
                width: 130
            },
            {
                field: 'invoiceNumber',
                title: '发票号码',
                width: 120
            },
            // {
            //     field: 'dutyParagraph',
            //     title: '税号',
            //     width: 150
            // },
            {
                field: 'electronInvoiceNumber',
                title: '数电发票号码',
                width: 150,
            },
            {
                field: 'taxRate',
                title: '税率',
                width: 120,
                formatter: function (value) {
                    if (value){
                        for(var j = 0; j < taxDict.length; j++){
                            if(taxDict[j].itemCode === value){
                                return taxDict[j].itemRemark;
                            }
                        }
                    }
                    return '';
                },
            },
            {
                field: 'currencyCode',
                title: '币种',
                width: 60
            },
            {
                field: 'taxAmount',
                title: '含税金额',
                width: 100,
                formatter: function (value) {
                    return formatterCustomPrice(value,2,true,false);
                },
            },
            {
                field: 'noTaxAmount',
                title: '未税金额',
                width: 100,
                formatter: function (value) {
                    return formatterCustomPrice(value,2,true,false);
                },
            },
            {
                field: 'diffTaxMoney',
                title: '税额',
                width: 100,
                formatter: function (value) {
                    return formatterCustomPrice(value,2,true,false);
                },
            },

        ]
    ]


    $(el.tbInvoice).edatagrid({
        name:'tbInvoiceTable',
        loadMsg: '数据加载中, 请耐心等待......',
        title: '发票明细',
        height: el.bodyHeight - $(el.dataDiv).outerHeight()-100,
        url: g.ctx + 'pc/finance/invoiced/receipt/rest/find/by/apply/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // rowHeight: 'auto',
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            iaId: $(el.id).val()
        },
        columns: columns,
        toolbar: toolbars,
        onClickRow: function (index) {
            initFileForm('invoice-file-form');
        },
        onLoadSuccess: function (data) {
            $('#tbInvoice').parent(".datagrid-view").children(".datagrid-view1")
                .children(".datagrid-body")
                .children(".datagrid-body-inner")
                .children(".datagrid-btable")
                .children("tbody")
                .children("tr")
                .children("td")
                .children(".datagrid-cell-rownumber").css('height', '60px').css('line-height', '60px')
            // if (data.rows.length>0){
            initFileForm('invoice-file-form');
            // }
            var rows = data.rows;
            for (var j = 0; j < rows.length; j++) {
                if (Number(rows[j].deductionStatus) === 3) {
                    $(el.tbInvoice).datagrid('selectRow', j);
                }
            }

        },
    });
}


function confirm(call){
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        formData.invoiceAllList = $(el.tbInvoice).datagrid('getRows');
        formData.invoiceSelectList = $(el.tbInvoice).datagrid('getSelections');
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/invoiced/apply/rest/redReversal',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }else {
        layer.msg('检验未通过!请检查红框未填');
        return false;
    }
}

/**
 * 财务确认
 *
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param call 回调函数
 */
function financeConfirm(approveStatus,call) {
    var approveOpinion = $(el.approveOpinion).val();
    var formData = {};
    var rows = $(el.tbInvoice).datagrid('getSelections')
    formData.id = $(el.id).val();
    formData.approveStatus = approveStatus;
    formData.approveOpinion = approveOpinion;
    formData.invoiceSelectList = rows;
    if(approveStatus===0&&!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    if(rows.length>0){
        //判断状态是否未红冲， 如果不是红冲不给确认
        for(var i = 0; i < rows.length; i++){
            if(Number(rows[i].deductionStatus)!==3){
                topWin.layer.alert('请选择发票状态为红冲发票', {icon: 0});
                return false;
            }
        }
    }
    if (rows.length===0){
        layer.confirm('未选择需要删除的红冲发票,是否继续？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            layer.closeAll()
            redReversalFinanceConfirmAjax(formData,call)
            return false;
        }, function(){
            layer.closeAll()
            return false;
        });
    }else {
        redReversalFinanceConfirmAjax(formData,call)
    }

}

function redReversalFinanceConfirmAjax(formData,call){
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/invoiced/apply/rest/redReversalFinanceConfirm',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            top.layer.close(loading);
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}
