/**
 * 对账模块-对账单查看页面
 *
 * Created by li.kui on 2020/8/6.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    orderType: '#orderType',
    supplierCode: '#supplierCode',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    tbApproveLog: '#tbApproveLog',
    paymentTermDesc: '#paymentTermDesc',
    paymentTermCode: '#paymentTermCode',
    taxCode: '#taxCode',
    purchaseGroup: '#purchaseGroup',
    poType: '#poType',
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - 80});
        },
        onExpand: function () {
            $(el.dataTabs).tabs('select', 0);

            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });

    findUserTableColumn();

    initTbDetails();

    initTbRebate();

    initTbDeduction();

    initTbApproveLog();
// 税率
    $(el.taxCode).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'newItemCodeAndName',
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=tax'
    });
    // 付款条件
    $(el.paymentTermCode).combobox({
        panelHeight: 'auto',
        // panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=supplier_fktj'
    });
    //采购组
    $(el.purchaseGroup).combobox({
        editable: true,
        required: false,
        valueField: 'purchaseGroupCode',
        textField: 'purchaseGroupName',
        panelHeight: '150',
        url: '/purchase/group/rest/list/all'
    });
    $(el.poType).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        multiple: true,
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=po_type'
    });
    getExchangeRate($(el.currencyCode).textbox('getValue'));
});


//下载
function downloadInvoiceFile(filePath,fileName) {
    if (fileName.indexOf(".pdf") != -1) {
        previewPDF(filePath,fileName);
    }else if (fileName.indexOf(".jpg") != -1 || fileName.indexOf(".png") != -1) {
        previewImgNew(filePath,fileName);
    }else {
        window.location.href = '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName);
    }
}
function previewPDF(filePath, fileName) {
    localStorage.pdf_url = '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName);
    openMainLayerWin("PDF文件预览", '/static/pdfjs1/web/viewer.html', "1000px;", "100%");
}
function previewImgNew(filePath, fileName) {
    layer.photos({
        photos: {
            "title": "图片预览",
            "start": 0,
            "data": [
                {
                    "alt": fileName,
                    "pid": 5,
                    "src": '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName)
                }
            ]
        }
    });
}

/**
 * 初始化入库明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);

    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/by/statement/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        autoRowHeight: false,
        queryParams: {
            asId: $(el.id).val(),
            deleteFlag:-1
        },
        columns: [
            tableColumns
        ],
        toolbar: [
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            // '-',
            // {
            //     text: '调整布局',
            //     iconCls: 'icon-man',
            //     handler: function () {
            //         adjustTableColumn();
            //     }
            // }
        ]
    });
}


/**
 * 初始化返利信息表格
 */
function initTbRebate() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbRebate).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/rebate/list',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'rebateId',
                    title: '附件查看',
                    width: 80,
                    formatter: function (value) {
                        if(value){
                            return '<a href="javascript:void(0)" onclick="lookDrAttachment(this)" data-type="2" data-id="' + value + '">查看</a>';
                        }
                        return '';
                    }
                },
                {
                    field: 'rebateNo',
                    title: '返利单号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'rebateType',
                    title: '返利类型',
                    width: 120,
                    sortable: true,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '购方对供方返利';
                        }
                        if(Number(value) === 2) {
                            return '供方对购方返利';
                        }
                        return '';
                    }
                },
                {
                    field: 'rebateAmount',
                    title: '含税返利金额(元)',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxCodeDesc',
                    title: '税率',
                    width: 160,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'rebateTime',
                    title: '返利时间',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                },
                {
                    field: 'rebateReason',
                    title: '返利原因',
                    width: 300
                },
                {
                    field: 'companyCode',
                    title: '公司代码',
                    width: 80
                },
                {
                    field: 'companyName',
                    title: '公司名称',
                    width: 180
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}


/**
 * 初始化扣款信息表格
 */
function initTbDeduction() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbDeduction).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/deduction/list',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        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: 'deductionNo',
                    title: '扣款编号',
                    width: 140,
                    sortable: true
                },
                {
                    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 '';
                    }
                }
            ]
        ]
    });
}


/**
 * 初始化审批记录表格
 */
function initTbApproveLog() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbApproveLog).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/as/approve/log',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'approveNode',
                    title: '审批节点描述',
                    width: 120,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '对账确认';
                        }else {
                            return '财务节点';
                        }
                    }
                },
                {
                    field: 'approveResult',
                    title: '审批结果',
                    width: 120,
                    formatter: function (value) {
                        switch (Number(value)){
                            case 0:
                                return '<span style="color: red;">拒绝</span>';
                            case 1:
                                return '<span style="color: green;">同意</span>';
                            case 2:
                                return '<span style="color: orange;">采购撤销</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'approveOpinion',
                    title: '审批意见',
                    width: 300
                },
                {
                    field: 'approveUserName',
                    title: '审批用户姓名',
                    width: 130
                },
                {
                    field: 'approveTime',
                    title: '审批时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}


/**
 * 入库明细导出
 */
function detailExport() {
    var rows = $(el.tbDetails).datagrid('getRows');
    $(el.tbDetails).datagrid('toExcel', {
        filename: '对账明细数据.xls',
        rows: rows,
        worksheet: '对账单明细'
    });
}


/**
 * 查看扣款或返利附件
 *
 * @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');
                }
            }
        ]
    });
}


/**
 * 调整表格列布局
 */
function adjustTableColumn() {
    var url = g.ctx + 'fin/common/adjust/table/column?pageTable=2';
    el.adjustTableColumnDialog = openDialog('adjustTableColumn', url, {
        title: '调整表格列布局',
        width: '970px',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.adjustTableColumnDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定并保存设置',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmAndSaveSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

                        initTbDetails();
                        el.adjustTableColumnDialog.dialog('close');
                    });
                }
            },
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

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


/**
 * 获取当前用户表格列布局
 */
function findUserTableColumn() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=2&isAuthority=1',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                el.userTableColumn.push(data[i].columnField);
            }
        }
    });
}


/**
 * 动态表格列
 */
// function dynamicColumns(orderType) {
//     var result = [];
//     //加一个删除标记
//     result.push(tableColumns[0]);
//     for(var i = 0; i < el.userTableColumn.length; i++){
//         var columnField = el.userTableColumn[i];
//
//         for(var j = 0; j < tableColumns.length; j++){
//             var column =  tableColumns[j];
//             if(column.field === columnField){
//
//                 if(column.field === 'materialSupplierCode' || column.field === 'materialSupplierName' || column.field === 'freightType'){
//                     column.hidden = Number(orderType) === 1;
//                 }
//
//                 result.push(column);
//                 break;
//             }
//         }
//     }
//
//     return result;
// }


// 报表所有列
var tableColumns = [
    {
        field: 'deleteFlag',
        title: '删除标记',
        width: 80,
        formatter: function (value) {
            if (value ===1) {
                return '<span style="color: red;">已删除</span>';
            }else {
                return "未删除";
            }
        }
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'receiveRowNo',
        title: '行号',
        width: 60,
        sortable: true
    },
    {
        field: 'receiveDate',
        title: '入库日期',
        width: 110,
        sortable: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 180,
        sortable: true
    },
    {
        field: 'specs',
        title: '规格',
        width: 120
    },

    {
        field: 'receiveNum',
        title: '入库数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        }
    },
    {
        field: 'materialUnit',
        title: '单位',
        width: 70,
        sortable: true
    },
    {
        field: 'orderTaxPrice',
        title: '订单含税单价',
        width: 90,
        sortable: true
    },

    // {
    //     field: 'asNtAmount',
    //     title: '订单未税金额',
    //     width: 100,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    // {
    //     field: 'asItAmount',
    //     title: '订单含税金额',
    //     width: 100,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    // {
    //     field: 'asDiffPrice',
    //     title: '对账差异单价',
    //     width: 90,
    //     sortable: true
    // },
    // {
    //     field: 'asDiffAmount',
    //     title: '对账差异含税金额',
    //     width: 130,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    // {
    //     // 累计开票金额 = 申请开票金额 + 采购确认金额 + 财务过账金额
    //     field: 'invoicedAmount',
    //     title: '累计开票金额',
    //     width: 110,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (!value) {
    //             return '0.00';
    //         }
    //         return formatNumber(value, 2, 1);
    //     }
    // },
    // {
    //     // 剩余可开票金额 = (入库数量-对账数量) * 订单含税单价
    //     field: 'surplusAmount',
    //     title: '剩余可开票金额',
    //     width: 120,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (!value) {
    //             return '0.00';
    //         }
    //         return formatNumber(value, 2, 1);
    //     }
    // },

    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },

    // {
    //     field: 'seekPgCodeName',
    //     title: '询源采购组',
    //     width: 110,
    //     sortable: true
    // },





    {
        field: 'paymentTermCodeName',
        title: '付款条件',
        width: 200,
        sortable: true
    },
    // {
    //     field: 'contractNo',
    //     title: '合同号',
    //     width: 120
    // },
    {
        field: 'inOutFlag',
        title: '出入库标识',
        width: 85,
        sortable: true
    },
    {
        field: 'receiveCode',
        title: '入库凭证',
        width: 90,
        sortable: true
    },
    {
        field: 'itemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'asQuantity',
        title: '本次对账数量',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        }
    },
    {
        field: 'notTaxPrice',
        title: '未税单价',
        width: 70,
        sortable: true
    },
    {
        field: 'orderNotTaxPrice',
        title: '订单未税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'taxAmount',
        title: '对账含税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }else {
                return formatNumber(value, 2, 1);
            }
        }
    },
    {
        field: 'diffTaxAmount',
        title: '对账税额',
        width: 90,
        sortable: true,
        formatter: function (value) {
            if (!value) {
                return '';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'notTaxAmount',
        title: '对账未税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }else {
                return formatNumber(value, 2, 1);
            }
        }
    },
    {
        field: 'taxPrice',
        title: '对账含税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'poTypeName',
        title: '订单类型名称',
        width: 100
    },
    {
        field: 'orderTaxCodeDesc',
        title: '订单税率',
        width: 160,
        sortable: true
    },
    {
        field: 'taxCodeDesc',
        title: '税率',
        width: 160,
        sortable: true
    },
    // {
    //     field: 'paymentWayCodeDesc',
    //     title: '付款方式',
    //     width: 200,
    //     sortable: true
    // },
    // 承运商对账
    // {
    //     field: 'materialSupplierCode',
    //     title: '材料商编码',
    //     width: 90,
    //     sortable: true
    // },
    // {
    //     field: 'materialSupplierName',
    //     title: '材料商名称',
    //     width: 180,
    //     sortable: true
    // },
    // {
    //     field: 'freightType',
    //     title: '运费类型',
    //     width: 80,
    //     sortable: true
    // },
    // 集采订单信息
    // {
    //     field: 'jcPoCode',
    //     title: '集采SAP订单号',
    //     width: 110,
    //     sortable: true
    // },
    // {
    //     field: 'jcPoItemNo',
    //     title: '行号',
    //     width: 70,
    //     sortable: true
    // },
    // {
    //     field: 'jcFactoryCode',
    //     title: '集采工厂',
    //     width: 80,
    //     sortable: true
    // }
];