/**
 * 对账模块-所有对账单列表首页JS
 *
 * Created by li.kui on 2020/12/29.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    orderType: '#orderType',
    searchForm: '#searchForm',
    companyCode: '#companyCode',
    supCodeOrName: '#supCodeOrName',
    statementNo: '#statementNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    status: '#status',
    isComplete: '#isComplete',
    oaProcessNo: '#oaProcessNo',
    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=1';
    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},
            {label: '对账单已确认', value: 9}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    // 初始化是否开票完成下拉框
    $(el.isComplete).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 数据状态 0:否 1:是
            {label: '全部', value: -1},
            {label: '否', value: 0},
            {label: '是', value: 1}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        url: comUrl,
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });
}


/**
 * 初始化页面表格
 */
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/account/statement/rest/all/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'status',
                    title: '数据状态',
                    width: 115,
                    sortable: true,
                    formatter: function (value) {
                        // 对账单数据状态 1:暂存对账单 2:待确认 3:采购拒绝对账单 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认对账单 8:财务驳回对账单 9:对账单已确认
                        // switch (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 '';
                        // }

                        //2-待主管确认、3-采购拒绝，7-待采购确认，8-采购拒绝对账单，9-对账单已确认
                        switch (value) {
                            case 1:
                                return '暂存对账单';
                            case 2:
                                return '<span style="color: blue;">待采购确认</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: 'accountStatementNo',
                    title: '对账单号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 140,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                    }
                }
            ]
        ],
        columns: [
            [
                // {
                //     field: 'oaProcessNo',
                //     title: 'OA申请单号',
                //     width: 140,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         var opId = row.oaProcessId;
                //         if(!row.oaProcessId){
                //             opId = value;
                //         }
                //         if(!opId){
                //             return '';
                //         }
                //         return '<a href="javascript:void(0)" onclick="lookOaApproveLog(this)" data-op="'+ opId +'">' + value + '</a>';
                //     }
                // },
                // {
                //     field: 'pushOaUserName',
                //     title: '推送OA员工姓名',
                //     width: 110,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         if(!row.oaProcessId && !row.oaProcessNo){
                //             return '';
                //         }
                //         return value;
                //     }
                // },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270,
                    sortable: true
                },
                {
                    field: 'taxAmount',
                    title: '对账含税金额',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                // {
                //     field: 'bpPayableBalance',
                //     title: '期初金额(暂估+应付)',
                //     width: 140,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         if (!value && !row.bpEstimateBalance) {
                //             return 0;
                //         }
                //         if(value && !row.bpEstimateBalance){
                //             return formatNumber(value, 2, 1);
                //         }
                //         if(!value && row.bpEstimateBalance){
                //             return formatNumber(row.bpEstimateBalance, 2, 1);
                //         }
                //
                //         return formatNumber(Number(value) + Number(row.bpEstimateBalance), 2, 1);
                //     }
                // },
                // {
                //     field: 'etPayableBalance',
                //     title: '期末金额(暂估+应付)',
                //     width: 140,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         if (!value && !row.etEstimateBalance) {
                //             return 0;
                //         }
                //         if(value && !row.etEstimateBalance){
                //             return formatNumber(value, 2, 1);
                //         }
                //         if(!value && row.etEstimateBalance){
                //             return formatNumber(row.etEstimateBalance, 2, 1);
                //         }
                //
                //         return formatNumber(Number(value) + Number(row.etEstimateBalance), 2, 1);
                //     }
                // },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'invoiceCompleteFlag',
                    title: '是否开票',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (Number(value) === 0) {
                            return '否';
                        }
                        return '<span style="color: green;">是</span>';
                    }
                },
                // {
                //     field: 'differenceAmount',
                //     title: '差异金额',
                //     width: 90,
                //     sortable: true,
                //     formatter: function (value) {
                //         if (!value) {
                //             return '';
                //         }
                //         return formatNumber(value, 2, 1);
                //     }
                // },
                {
                    field: 'companyCode',
                    title: '采购公司',
                    width: 240,
                    sortable: true,
                    formatter: function (value, row) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 130,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'updateTime',
                    title: '最后更新时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'remark',
                    title: '备注',
                    width: 260,
                    formatter: function (value) {
                        if(value){
                            return '<span style="display: inline-block;width: 260px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title="' + value + '">' + value + '</span>';
                        }
                        return '';
                    }
                },
                // {
                //     field: 'purchaseUser',
                //     title: '采购员',
                //     width: 140,
                // },
                {
                    field: 'emptyColumn',
                    title: '',
                    width: 20
                }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    detail(2);
                }
            },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportStatementOrder();
            //     }
            // }
        ],
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}


/**
 * 查看对账单
 */
function lookStatementOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'fin/account/statement/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');
                }
            }
        ]
    });
}

/**
 * 新增对账单
 * optType 操作类型；0-新增；1-编辑；2-查看；3-主管确认；4-财务确认
 */
function detail(optType) {
    var id = '';
    if (optType!==0){
        var row = $(el.tb).datagrid('getSelected'), userId = $(el.userId).val();
        if (!row) {
            topWin.layer.alert('请选中一条记录', {icon: 0});
            return false;
        }
        id = row.id;
    }

    var url = g.ctx + 'pc/finance/account/statement/detail?id='+ id+'&optType='+optType;
    var buttons = [];
    if (optType===0||optType===1){
        buttons.push(
            {
                text: '暂存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['addStatementOrder'].dataSave(0,function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.addOrEditDialog.dialog('close');
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }else if (optType===2){
        buttons.push(
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }else if (optType===3){
        buttons.push(
            {
                text: '通过',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['addStatementOrder'].purchaseSave(function (data) {
                        purchaseApprove(1, data);
                    });
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['addStatementOrder'].purchaseRefuseStatement(function (data) {
                        purchaseApprove(0, data);
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }
    el.addOrEditDialog = openDialog('addStatementOrder', url, {
        title: optType===0?'新增对账单':optType===1?'编辑对账单':optType===2?'查看对账单':optType===3?'采购确认对账单':'财务确认对账单',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addOrEditDialog.dialog('destroy');
        },
        buttons: buttons
    });
}
/**
 * 导出对账单
 */
function exportStatementOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }

    var url = g.ctx + 'fin/account/statement/rest/data/export?asId=' + row.id;
    window.open(url);
}


/**
 * 查询对账单数据
 */
function searchAsData() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.statementNo = $.trim($(el.statementNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.createUserName = $.trim($('#createUserName').val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.isComplete = $(el.isComplete).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.orderType = $(el.orderType).val();
    $(el.tb).datagrid('load');
}


/**
 * 重置查询
 */
function resetAsSearch() {
    $(el.supCodeOrName).val('');
    $('#createUserName').val('');
    $(el.statementNo).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.isComplete).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');

    searchAsData();
}


/**
 * 查看OA审批日志
 *
 * @param ele 当前操作的DOM节点
 */
function lookOaApproveLog(ele) {
    var url = g.ctx + 'fin/common/look/oa/log/dialog?oaProcessNo=' + $(ele).data('op');
    var lookOaLogDialog = openDialog('lookOaApproveLog', 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');
                }
            }
        ]
    });
}