/**
 * 开票申请，公共页签
 * Created by heqiaohui on 2021/4/30.
 */
'use strict';

/**
 * 文档就绪
 */
$(function () {
    // $(el.dataPanel).panel({
    //     collapsible: true,
    //     onCollapse: function () {
    //         $(el.tbDeduction).edatagrid('resize', {height: el.bodyHeight - 80});
    //     },
    //     onExpand: function () {
    //         var dataDiv = $(el.dataDiv).outerHeight() + 90;
    //         $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
    //     }
    // });
    initDeduction();
});

/**
 * 初始化关联发票表格
 */
function initDeduction() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;
    var toolbars = [
        {
            text: '获取扣款信息',
            iconCls: 'icon-add',
            handler: function () {
                findDeductionDetail();
            }
        }
    ];
    var columns;
    $(el.tbDeduction).edatagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/deduction/list',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        remoteSort: false,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                // {
                //     field: 'deductionId',
                //     title: '附件查看',
                //     width: 80,
                //     formatter: function (value) {
                //         if(value){
                //             return '<a href="javascript:void(0)" onclick="lookDrAttachment(this)" data-type="1" data-id="' + value + '">查看</a>';
                //         }
                //         return '';
                //     }
                // },
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'deductionNo',
                    title: '扣款编号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'shareFlag',
                    title: '是否分摊',
                    width: 80,
                    sortable: true,
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 0:
                                return '<span style="color: green;">不需要</span>';
                            case 1:
                                return '<span style="color: red;">需要</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deductionTypeDesc',
                    title: '扣款类型',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'deductionAmount',
                    title: '含税扣款金额(元)',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxCodeDesc',
                    title: '税率',
                    width: 160,
                    sortable: true
                },
                {
                    field: 'deductionTime',
                    title: '扣款时间',
                    width: 90,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'deductionReason',
                    title: '扣款原因',
                    width: 300
                },
                {
                    field: 'companyCode',
                    title: '公司代码',
                    width: 80
                },
                {
                    field: 'companyName',
                    title: '公司名称',
                    width: 180
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270
                },
                // {
                //     field: 'associatedNo',
                //     title: 'SRM业务单据',
                //     width: 140,
                //     formatter: function (value, row) {
                //         if(!row.associatedRowNo){
                //             return value;
                //         }else {
                //             return value + '|' + row.associatedRowNo;
                //         }
                //     }
                // },
                // {
                //     field: 'associatedOaNo',
                //     title: 'OA流程单号',
                //     width: 120,
                //     sortable: true
                // },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                },
                {
                    field: 'erpSyncState',
                    title: 'ERP处理状态',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value === '' || value === null || value === undefined) return '';
                        return value === 0 ? "<span style='color: green;'>成功</span>" : '<span style="color: red;">失败</span>';
                    }
                },
                {
                    field: 'erpSyncMessage', title: 'ERP处理反馈', width: '130', //hidden:true,
                    align: 'center'
                },{
                field: 'erpSyncNo', title: 'ERP扣款凭证号', width: '130', //hidden:true,
                align: 'center'
            },{
                field: 'erpSyncYear', title: 'ERP扣款凭证年度', width: '130', //hidden:true,
                align: 'center'
            },{
                field: 'erpSyncTime',
                title: 'ERP处理时间',
                width: 140,
                sortable: true,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD HH:mm:ss");
                    }
                    return '';
                }
            },
            ]
        ],
        toolbar: [
            {
                id: 'btn_export',
                text: '导出Excel',
                iconCls: 'icon-download',
                handler: function () {
                    exportDeductionData();
                }
            }
        ],
        onSelect: function () {
            refreshDeduction();
        },
        onUnselect: function () {
            refreshDeduction();
        },
        onSelectAll: function () {
            refreshDeduction();
        },
        onUnselectAll: function () {
            refreshDeduction();
        },
        onLoadSuccess: function (data) {
            if (deductionAddFlag===1){
                $(el.tbDeduction).datagrid('selectAll');
            }else {
                var rows = data.rows;
                for (var j = 0; j < rows.length; j++) {
                    if (Number(rows[j].useFlag) === 1) {
                        $(el.tbDeduction).datagrid('selectRow', j);
                    }
                }
            }
        },
        // toolbar: toolbars,
    });
}

/**
 * 刷新扣款
 */
function refreshDeduction() {
    if (deductionRefreshFlag===1){
        calculationDeductionPageAmount();
    }
}

function  calculationDeductionPageAmount() {
    var rows = $(el.tbDeduction).datagrid('getSelections');
    var deductionAmountTotal = new BigNumber(0);
    for (var n = 0; n < rows.length; n++) {
        var item = rows[n];
        if (Number(item.shareFlag)===0){
            deductionAmountTotal = deductionAmountTotal.plus(item.deductionAmount)
        }
    }
    var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
    var strikePriceAmount = new BigNumber(0);
    if ($(el.strikePriceAmount).textbox('getValue')){
        strikePriceAmount = $(el.strikePriceAmount).textbox('getValue').replace(/,/g,'');
        strikePriceAmount = new BigNumber(strikePriceAmount);
    }else {
        $(el.strikePriceAmount).textbox('setValue',strikePriceAmount);
    }
    $(el.actualUnpaidAmount).textbox('setValue', new BigNumber(invoiceTaxAmount.replace(/,/g,'')).minus(strikePriceAmount).plus(deductionAmountTotal).toFormat(2));
    $(el.deductionAmountTotal).textbox('setValue', deductionAmountTotal.toFormat(2));
}


function exportDeductionData() {
    var detailAll = $(el.tbDeduction).datagrid('getRows')

    var deductionIds = [];
    for (let i = 0 ; i < detailAll.length ; i ++){
        deductionIds.push(detailAll[i].deductionId);
    }

    topWin.layer.confirm('您确定要导出扣款数据?', {icon: 3}, function (index) {
        topWin.layer.close(index);
        var url = g.ctx + 'fin/deduction/manage/rest/export?deductionIds=' + deductionIds.join(",")+'&queryForm=1';
        window.open(url);
    });
}

/**
 * 获取扣款明细数据
 */
function findDeductionDetail(supplierCode,companyCode) {


    if(!supplierCode){
        topWin.layer.alert('请选择供应商信息', {icon: 0});
        return false;
    }

    if(!companyCode){
        topWin.layer.alert('请选择采购公司', {icon: 0});
        return false;
    }

    var queryParams = $(el.tbDeduction).datagrid('options').queryParams;
    queryParams.page = 1;
    queryParams.rows = 1000;
    queryParams.whether = 0;
    queryParams.queryForm = 2;
    queryParams.companyCode = companyCode;
    queryParams.supplierCode = supplierCode;
    $(el.tbDeduction).datagrid('options').url = g.ctx + 'fin/deduction/manage/rest/list';
    $(el.tbDeduction).datagrid('load');



}


/**
 * 获取扣款明细数据
 * flag = 0新建;
 */
function getDeductionDetail() {
    var detailAll = $(el.tbDeduction).datagrid('getRows')
    var detailSelect = $(el.tbDeduction).datagrid('getSelections')

    var detail = [];
    for (let i = 0 ; i < detailAll.length ; i ++){
        var obj = {};
        if (Number(deductionAddFlag)===0){
            obj.id = detailAll[i].id;
        }
        obj.asId = $(el.id).val();
        obj.deductionId = detailAll[i].deductionId;
        var useFlag = 0;
        for (let j = 0 ; j < detailSelect.length ; j ++){
            if (detailAll[i].deductionId===detailSelect[j].deductionId){
                useFlag = 1;
                break;
            }
        }
        obj.useFlag = useFlag;
        detail.push(obj);
    }
    console.log(JSON.stringify(detail))
    return detail;
}

// function getDeductionDetail() {
//     var detailAll = $(el.tbDeduction).datagrid('getRows')
//     var detailSelect = $(el.tbDeduction).datagrid('getSelections')
//
//     var detail = [];
//     for (let i = 0 ; i < detailSelect.length ; i ++){
//         var obj = {};
//         if (Number(deductionAddFlag)===0){
//             obj.id = detailAll[i].id;
//         }
//         obj.asId = $(el.id).val();
//         obj.deductionId = detailAll[i].deductionId;
//         obj.useFlag = 1;
//         detail.push(obj);
//     }
//     console.log(JSON.stringify(detail))
//     return detail;
// }


/**
 * 查看扣款或返利附件
 *
 * @param ele 当前操作DOM节点
 */
function lookDrAttachment(ele) {
    var drId = $(ele).data('id'), attType = $(ele).data('type');
    var url = g.ctx + 'fin/common/look/dr/attachment?drId=' + drId + '&attType=' + attType;
    var lookDrAttDialog = openDialog('lookDrAtt', url, {
        title: '附件查看',
        width: '35%',
        height: '45%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            lookDrAttDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    lookDrAttDialog.dialog('close');
                }
            }
        ]
    });
}
