/**
 * 对账模块-供应商账管理首页JS
 *
 * Created by 邓京术 on 2025/07/22.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    userId: '#userId',
    searchForm: '#searchForm',
    purchaseGroup: '#purchaseGroup',
    supCodeOrName: '#supCodeOrName',
    paymentPlanNo: '#paymentPlanNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    // createTimeStarts:'#createTimeStarts',
    status: '#status',
    paymentPlanYear: '#paymentPlanYear',
    paymentPlanMonth: '#paymentPlanMonth',
    createUserName: '#createUserName',
    tb: '#tb',
    addOrEditDialog: null,
    optConfirmDialog: null,
    newPaymentPlanDialog: null,
    defaultColumns: [],
    lookDialog: null,
    summaryDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    // initDict('payment_method,payment_way')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll')
    initComBoBoxData();

    el.defaultColumns = [
        {
            field: 'status',
            title: '数据状态',
            width: 115,
            sortable: true,
            exportEnum:[
                {code:1,codeWithDesc:'暂存'},
                {code:2,codeWithDesc:'待采购主管确认'},
                {code:3,codeWithDesc:'采购拒绝'},
                {code:4,codeWithDesc:'待财务确认'},
                {code:5,codeWithDesc:'财务拒绝'},
                {code:6,codeWithDesc:'已发布'},
            ],
            formatter: function (value) {
                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;">待财务确认</span>';
                    case 5:
                        return '<span style="color: red;">财务拒绝</span>';
                    case 6:
                        return '<span style="color: green;">已发布</span>';
                    default:
                        return '';
                }
            }
        },
        {
            field: 'paymentPlanNo',
            title: '采购预算单号',
            width: 140,
            sortable: true
        },
        {
            field: 'paymentPlanYear',
            title: '付款计划年份',
            width: 100,
            sortable: true
        },
        {
            field: 'paymentPlanMonth',
            title: '付款计划月份',
            width: 100,
            sortable: true
        } ,
        {
            field: 'planType',
            title: '控制维度',
            width: 100,
            sortable: true,
            formatter: function (value) {
                if (!value) {
                    return '不区分预付和月结';
                } else if (value === 'Y') {
                    return '区分预付和月结';
                } else {
                    return '不区分预付和月结';
                }
            }
        } ,
        {
            field: 'createUserName',
            title: '制单人',
            width: 100,
            sortable: true
        },
        {
            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: 'updateUserName',
            title: '最后更新人',
            width: 100,
            sortable: true
        },
        {
            field: 'updateTime',
            title: '最后更新时间',
            width: 140,
            sortable: true,
            exportDateFormatter:'dateTime',
            formatter: function (value) {
                if (!value) {
                    return '';
                }
                return moment(value).format('YYYY-MM-DD HH:mm');
            }
        },
        {
            field: 'remark',
            title: '备注',
            width: 120,
            sortable: true
        }
    ];
    //供应商不能看到的字段
    // if (Number($(el.isSupplier).val())===1){
    //     el.defaultColumns = el.defaultColumns.filter(obj => obj.field !== 'paymentExpireDate');
    // }
    //从后台查询动态列
    // let column = getRemoteColumnSort(columnSortCodeEnum.ACCOUNT_STATEMENT_SUP,el.defaultColumns);
    let column = el.defaultColumns;
    //赋值到表
    loadGrid(column);
});


/**
 * 初始化页面下拉框数据
 */
function initComBoBoxData() {
    var isSupplier = $(el.isSupplier).val(), comUrl = g.ctx + 'pc/sys/company/rest/listAll?userId='+$(el.userId).val();
    if(Number(isSupplier) === 1){
        comUrl = g.ctx + 'pc/sys/company/rest/listAll';
    }
    // 初始化状态下拉框
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 付款计划单数据状态 1:暂存 2:待采购主管确认 3:采购拒绝 4:待财务确认 5:财务驳回 6:已发布
            {label: '全部', value: -1},
            {label: '暂存', value: 1},
            {label: '待采购主管确认', value: 2},
            {label: '采购拒绝', value: 3},
            {label: '待财务确认', value: 4},
            {label: '财务拒绝', value: 5},
            {label: '已发布', value: 6}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    //初始化日期
    var months = [];

    for (let i = 1; i <= 12; i++) {
        let paddedNumber = i.toString().padStart(2, '0');
        months.push({
            label: paddedNumber,
            value: paddedNumber
        });
    }

    $('#paymentPlanMonth').combobox({
        data: months,
        valueField: 'value',
        textField: 'label'
    });

}

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

    var _index=-1;//记录编辑行号
    var _flag=false;//记录是否处于编辑状态
    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        url: g.ctx + 'pc/finance/payment/plan/rest/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
                },
            ]
        ],
        columns: [column],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    detail(2);
                    setOperationLog("查看按钮", "付款计划");

                }
            },
            '-',
            {
                text: '新增',
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    addNewPayPlan();
                }
            },
            '-',
            {
                text: '编辑',
                iconCls: 'icon-edit',
                id: 'btn_edit',
                handler: function () {
                    detail(1);
                    setOperationLog("编辑按钮", "付款计划");

                }
            },
            // '-',
            // {
            //     text: '提交确认',
            //     iconCls: 'icon-ok',
            //     id: 'btn_submit',
            //     handler: function () {
            //         submitConfirm();
            //     }
            // },
            '-',
            {
                text: '采购主管确认',
                iconCls: 'icon-ok',
                id: 'btn_purchase_submit',
                handler: function () {
                    detail(3);
                    setOperationLog("采购主管确认按钮", "付款计划");
                }
            },
            '-',
            {
                text: '财务确认',
                iconCls: 'icon-ok',
                id: 'btn_finance_submit',
                handler: function () {
                    detail(4);
                    setOperationLog("财务确认按钮", "付款计划");
                }
            },
            '-',
            {
                text: '查看明细',
                iconCls: 'icon-find',
                id: 'btn_detail',
                handler: function () {
                    look();
                    setOperationLog("查看明细按钮", "付款计划");
                }
            },
            '-',
            {
                text: '查看汇总',
                iconCls: 'icon-find',
                id: 'btn_summary',
                handler: function () {
                    summary();
                    setOperationLog("查看汇总按钮", "付款计划");
                }
            },
            // '-',
            // {
            //     text: '列表导出',
            //     iconCls: 'icon-redo',
            //     id: 'btn_list_export',
            //     handler: function () {
            //         openExportDialog('pc/finance/account/statement/rest/sup/export','tb', getQuery());
            //     }
            // }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("fin.payment.plan.index");
            $(el.tb).datagrid('clearSelections');
            reloadOk = true;
        },
        onBeforeLoad: function (param) {
            displayButtonByUserRole('fin.payment.plan.index');
            reloadOk = false;
        },
        // onCheck: function (index, row) {
        //     // 对账单数据状态 1:暂存 2:待采购主管确认 3:采购拒绝 4:待财务确认 5:财务驳回 6:已发布
        //     // var status = row.status;
        //     // // var paymentWay = row.paymentWay;
        //     // // var signFileStatus = row.signFileStatus;
        //     // // var signStatus = row.signStatus;
        //     // // 按钮 0:查看 1:新增 2:编辑 3:删除 4:提交确认 5:导出
        //     // var btn = $('div.datagrid-toolbar a');
        //     // debugger
        //     // switch (Number(status)) {
        //     //     case 1:
        //     //         btn.eq(2).linkbutton('enable');
        //     //         btn.eq(3).linkbutton('enable');
        //     //         btn.eq(4).linkbutton('enable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 2:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 3:
        //     //         btn.eq(2).linkbutton('enable');
        //     //         btn.eq(3).linkbutton('enable');
        //     //         btn.eq(4).linkbutton('enable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 4:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 5:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 6:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 7:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 8:
        //     //         btn.eq(2).linkbutton('enable');
        //     //         btn.eq(3).linkbutton('enable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('disable');
        //     //         btn.eq(6).linkbutton('disable');
        //     //         btn.eq(7).linkbutton('disable');
        //     //         btn.eq(11).linkbutton('disable');
        //     //         btn.eq(12).linkbutton('disable');
        //     //         break;
        //     //     case 9:
        //     //         btn.eq(2).linkbutton('disable');
        //     //         btn.eq(3).linkbutton('disable');
        //     //         btn.eq(4).linkbutton('disable');
        //     //         btn.eq(5).linkbutton('enable');
        //     //         btn.eq(6).linkbutton('enable');
        //     //         btn.eq(7).linkbutton('enable');
        //     //         // //购销合同签署
        //     //         // if(paymentWay == "C"){
        //     //         //     btn.eq(11).linkbutton('enable');
        //     //         //     btn.eq(12).linkbutton('enable');
        //     //         // }
        //     //         break;
        //     //     default:
        //     //         break;
        //     }
        //     if (row.deleteFlag!==0){
        //         btn.eq(4).linkbutton('disable');
        //     }
        // },
        onClickRow: function (index, row) {
            // 对账单数据状态 1:暂存 2:待采购主管确认 3:采购拒绝 4:待财务确认 5:财务驳回 6:已发布
            var status = row.status;

            // 按钮 0:查看 1:新增 2:编辑 3:删除 4:提交审批 5:导出
            var btn = $('div.datagrid-toolbar a');
            // switch (Number(status)) {
            //     case 1:
            //         btn.eq(2).linkbutton('enable');
            //         btn.eq(3).linkbutton('enable');
            //         btn.eq(4).linkbutton('enable');
            //         btn.eq(5).linkbutton('disable');
            //         break;
            //     case 2:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //         break;
            //     case 3:
            //         btn.eq(2).linkbutton('enable');
            //         btn.eq(3).linkbutton('enable');
            //         btn.eq(4).linkbutton('enable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 4:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 5:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 6:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 7:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 8:
            //         btn.eq(2).linkbutton('enable');
            //         btn.eq(3).linkbutton('enable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('disable');
            //
            //         break;
            //     case 9:
            //         btn.eq(2).linkbutton('disable');
            //         btn.eq(3).linkbutton('disable');
            //         btn.eq(4).linkbutton('disable');
            //         btn.eq(5).linkbutton('enable');
            //
            //         break;
            //     default:
            //         break;
            // }
            // if (row.deleteFlag!==0){
            //     btn.eq(4).linkbutton('disable');
            // }
        }
    });
}

function summary() {
    var id = '';
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    id = row.id;
    let btns = [
        {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                el.summaryDialog.dialog('close');
            }
        }
    ]
    // let rows = $('#tb').datagrid('getChecked');
    // //判断数据是否都是全部失败
    // let ids = []
    // for (let i = 0; i < rows.length; i++) {
    //     ids.push(rows[i].id)
    // }
    el.summaryDialog = openDialog('summaryDialog', g.ctx + 'pc/finance/payment/plan/summary?id='+id, {
        title: '付款计划汇总查看',
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            $(el.tb).datagrid('reload');
            el.summaryDialog.dialog('destroy');
        },
        buttons: btns
    });

}

function look() {
    var id = '';
    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/payment/plan/look?id='+id+'&optType=2';
    var buttons = [];
    buttons.push(
        {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                $(el.tb).datagrid('reload');
                el.lookDialog.dialog('close');
            }
        }
    );
    el.lookDialog = openDialog('lookPaymentPlan', url, {
        title: '',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDialog.dialog('destroy');
        },
        buttons: buttons
    });
}

/**
 * 新增对账单
 * 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;
        }
        //采购主管确认 3 财务确认 4
        //全部明细数据都为 提交状态才能 主管确认。
        if (optType===3 && (row.status === 6 || row.status === 4)) {
            topWin.layer.alert('该状态不支持采购主管确认', {icon: 0});
            return false;
        }
        //状态为4 才是待财务确认  optType===4 财务确认
        if (optType===4 && (row.status !== 4)) {
            topWin.layer.alert('该状态不支持财务确认', {icon: 0});
            return false;
        }

        //状态为1 才是待财务确认  optType===1 编辑
        if (optType===1 && (row.status === 4 ||　row.status === 6)) {
            topWin.layer.alert('该状态不能编辑', {icon: 0});
            return false;
        }


        id = row.id;
    }

    var url = g.ctx + 'pc/finance/payment/plan/detail?id='+id+'&optType='+optType;
    var buttons = [];
    if (optType===0||optType===1) {
        buttons.push(
            // {
            //     text: '暂存',
            //     iconCls: 'icon-save',
            //     handler: function () {
            //         topWin.frames['addPaymentPlan'].dataSave(0,function () {
            //             topWin.layer.msg('数据保存成功', {icon: 1});
            //             $(el.tb).datagrid('load');
            //             el.addOrEditDialog.dialog('close');
            //         });
            //     }
            // },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['addPaymentPlan'].checkDataSave(0,function () {
                        topWin.layer.msg('数据加载成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        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-save',
            handler: function () {
                topWin.frames['addPaymentPlan'].approvalPayment(3,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===4) {//账务确认
        buttons.push(
        {
            text: '通过',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['addPaymentPlan'].approvalPayment(4, function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    $(el.tb).datagrid('load');
                    el.addOrEditDialog.dialog('close');
                });
            }
        },
        {
            text: '拒绝',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['addPaymentPlan'].approvalPayment(5, 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');
            }
        });
    }
    el.addOrEditDialog = openDialog('addPaymentPlan', 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 addNewPayPlan() {
    var url = g.ctx + 'pc/finance/payment/plan/newPaymentPlan?id=';
    var buttons = [];
        buttons.push(
            {
                text: '提交',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['newPaymentPlan'].submitPaymentPlanSave(0,function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.newPaymentPlanDialog.dialog('close');
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.newPaymentPlanDialog.dialog('close');
                }
            }
        );

    el.newPaymentPlanDialog = openDialog('newPaymentPlan', url, {
        title: '新增付款计划单',
        width: '50%',
        height: '60%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.newPaymentPlanDialog.dialog('destroy');
        },
        buttons: buttons
    });
}


/**
 * 列表上提交确认
 */
function submitConfirm() {
    var row = $(el.tb).datagrid('getSelected'), ids = [];
    if (!row) {
        topWin.layer.alert('请选择您需要提交的对账单进行操作', {icon: 0});
        return false;
    }

    if(Number(row.status) === 1 || Number(row.status) === 3){
        ids.push(row.id);
    }else {
        topWin.layer.alert('只有暂存或者采购拒绝的对账单才能提交确认', {icon: 0});
        return false;
    }

    topWin.layer.confirm('您确定要提交选中的对账单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/account/statement/rest/submit/confirm',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('提交成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}


/**
 * 数据保存后提交
 *
 * @param statementId 对账单ID
 */
function dataSaveSubmit(statementId) {
    var ids = [];
    ids.push(statementId);

    var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'fin/account/statement/rest/submit/confirm',
        type: 'POST',
        data: {ids: JSON.stringify(ids)},
        success: function () {
            topWin.layer.close(loading);
            $(el.tb).datagrid('reload');

            var tab = parent.$('#app_main_tab').tabs('getSelected');
            parent.tabAdd("采购对账确认", "/fin/account/statement/purchase/index", 1000000576, true);

            var index = parent.$('#app_main_tab').tabs('getTabIndex', tab);
            parent.$('#app_main_tab').tabs('close', index);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 操作确认
 *
 * @param roleType 1:采购 2:财务
 */
function optConfirm(roleType) {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length !== 1) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }
    var status = rows[0].status, id = rows[0].id, dialogTitle = '确认对账单';
    var url = g.ctx + 'fin/account/statement/opt/confirm?id=' + id + '&roleType=' + roleType;
    if(1 === roleType){
        if(Number(status) === 2 || Number(status) === 6 || Number(status) === 8){
            dialogTitle = '采购确认对账单'
        }else {
            topWin.layer.alert('采购只能操作待采购确认状态的对账单', {icon: 0});
            return false;
        }
    }else {
        if(Number(status) !== 7){
            topWin.layer.alert('财务只能操作待财务确认状态的对账单', {icon: 0});
            return false;
        }

        dialogTitle = '财务确认对账单';
    }

    openOptConfirmDialog(roleType, url, dialogTitle);
}


/**
 * 打开对账单确认页面
 *
 * @param roleType 1:采购 2:财务
 * @param url 页面URL
 * @param title 弹框标题
 */
function openOptConfirmDialog(roleType, url, title) {
    el.optConfirmDialog = openDialog('optConfirm', url, {
        title: title,
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.optConfirmDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '通过',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['optConfirm'].dataSave(function (data) {
                        if(!data.approveOpinion){
                            topWin.layer.alert('请输入审批意见', {icon: 0});
                            return false;
                        }
                        purchaseApprove(roleType, 1, data);
                    });
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['optConfirm'].dataSave(function (data) {
                        if(!data.approveOpinion){
                            topWin.layer.alert('请输入审批意见', {icon: 0});
                            return false;
                        }
                        purchaseApprove(roleType, 2, data);
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    $(el.tb).datagrid('reload');
                    el.optConfirmDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 采购审批
 *
 * @param roleType 1:采购 2:财务
 * @param approveStatus 1:通过 2:拒绝
 * @param submitData 提交数据
 */
function purchaseApprove(roleType, approveStatus, submitData) {
    submitData.roleType = 1;
    submitData.approveStatus = approveStatus;

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'fin/account/statement/rest/approve',
        type: 'POST',
        data: JSON.stringify(submitData),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            el.optConfirmDialog.dialog('close');
            $(el.tb).datagrid('reload');

            if(data){
                topWin.layer.msg(data, {icon: 1});
            }else {
                topWin.layer.msg('操作成功', {icon: 1});
            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 导出对账单
 */
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() {
    $(el.tb).datagrid('options').queryParams = getQuery();
    $(el.tb).datagrid('load');
}

function getQuery() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.paymentPlanNo = $.trim($(el.paymentPlanNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.createUserName = $.trim($(el.createUserName).val());
    queryParams.paymentPlanMonth = $(el.paymentPlanMonth).val();
    queryParams.paymentPlanYear = $(el.paymentPlanYear).val();
    return queryParams;
}


/**
 * 重置查询
 */
function resetAsSearch() {
    $(el.paymentPlanNo).val('');
    $(el.supCodeOrName).val('');
    $(el.purchaseGroup).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $(el.paymentPlanYear).val('');
    $(el.createUserName).val('');
    $(el.paymentPlanMonth).combobox('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');
                }
            }
        ]
    });
}

