/**
 * 对账模块-供应商账管理首页JS
 *
 * Created by li.kui on 2020/8/18.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    restrictFlag: '#restrictFlag',
    userId: '#userId',
    orderType: '#orderType',
    searchForm: '#searchForm',
    companyCode: '#companyCode',
    paymentWay:'#paymentWay',
    purchaseGroup: '#purchaseGroup',
    supCodeOrName: '#supCodeOrName',
    statementNo: '#statementNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    createTimeStarts:'#createTimeStarts',
    status: '#status',
    isComplete: '#isComplete',
    paymentStatus: '#paymentStatus',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    currencyCode:'#currencyCode',
    // oaProcessNo: '#oaProcessNo',
    tb: '#tb',
    addOrEditDialog: null,
    contractFileUpload: null,
    optConfirmDialog: null,
    defaultColumns: [],
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    initDict('payment_method,payment_way')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/company/rest/listAll,pc/sys/tax/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:'待推送OA审批'},
                {code:5,codeWithDesc:'OA审批中'},
                {code:6,codeWithDesc:'OA审批不通过'},
                {code:7,codeWithDesc:'待财务确认'},
                {code:8,codeWithDesc:'财务拒绝对账单'},
                {code:9,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;">待推送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: 'signFileStatus',
            title: '签章文件状态',
            width: 115,
            sortable: true,
            exportEnum:[
                {code:0,codeWithDesc:'待上传签章文件'},
                {code:1,codeWithDesc:'已上传签章文件'}
            ],
            formatter: function (value,row) {
                if (value===1){
                    return '<span style="color: green;">已上传签章文件</span>';
                }else {
                    return '<span style="color: grey;">待上传签章文件</span>';
                }
            }
        },
        {
            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: 'currencyCode',
            title: '币种',
            width: 70,
            sortable: true
        },
        {
            field: 'invoiceCompleteFlag',
            title: '是否开票',
            width: 100,
            sortable: true,
            exportEnum:[
                {code:0,codeWithDesc:'否'},
                {code:1,codeWithDesc:'是'}
            ],
            formatter: function (value) {
                if (Number(value) === 0) {
                    return '否';
                }
                return '<span style="color: green;">是</span>';
            }
        },
        {
            field: 'paymentWay',
            title: '付款方式',
            width: 100,
            sortable: true,
            exportEnum:getDictList('payment_way'),
            formatter: function (value) {
                return getDicName('payment_way',value);
            }
        },
        {
            field: 'paymentExpireDate',
            title: '付款到期日',
            width: 120,
            sortable: true,
            exportDateFormatter:'date',
            formatter: function (value, row) {
                if (!value) {
                    return '';
                }
                return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
            }
        },
        {
            field: 'companyCode',
            title: '采购公司',
            width: 240,
            sortable: true,
            exportEnum:getNecessaryDataList('pc/sys/company/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/company/rest/listAll',value);
            }
        },
        {
            field: 'signStatus',
            title: '签署状态',
            width: 115,
            sortable: true,
            exportEnum:[
                {code:0,codeWithDesc:'草稿'},
                {code:1,codeWithDesc:'签署中'},
                {code:2,codeWithDesc:'完成'},
                {code:3,codeWithDesc:'已过期'},
                {code:4,codeWithDesc:'已拒签'},
                {code:5,codeWithDesc:'已作废'},
                {code:6,codeWithDesc:'作废中'}
            ],
            formatter: function (value) {
                switch (value) {
                    case 0:
                        return '<span style="color: grey;">草稿</span>';
                    case 1:
                        return '<span style="color: blue;">签署中</span>';
                    case 2:
                        return '<span style="color: green;">完成</span>';
                    case 3:
                        return '<span style="color: orange;">已过期</span>';
                    case 4:
                        return '<span style="color: red;">已拒签</span>';
                    case 5:
                        return '<span style="color: dimgrey;">已作废</span>';
                    case 6:
                        return '<span style="color: blue;">作废中</span>';
                    default:
                        return '';
                }
            }
        },
        {
            field: 'signOrder',
            title: '签章顺序',
            width: '10%' ,
            exportEnum:[
                {code:1,codeWithDesc:'乙方先签章'},
                {code:2,codeWithDesc:'甲方先签章'},
                {code:3,codeWithDesc:'单签甲方'}
            ],
            formatter: function (value) {
                if (value==="1"){
                    return '乙方先签章';
                }else if (value==="2"){
                    return '甲方先签章';

                }else if (value==="3"){
                    return '单签甲方';
                }else {
                    return '';
                }
            }
        },
        {
            field: 'accountStatementNo',
            title: '对账单号',
            width: 140,
            sortable: true
        },
        {
            field: 'accountStatementYear',
            title: '对账单年份',
            width: 100,
            sortable: true
        },
        {
            field: 'accountStatementMonth',
            title: '对账单月份',
            width: 100,
            sortable: true
        } ,
        {
            field: 'invoicedCode',
            title: 'MIRO凭证号',
            width: 100,
            sortable: true,
        },
        {
            field: 'invoiceNo',
            title: '到票发票号',
            width: 100,
            sortable: true,
        },
        {
            field: 'purchaseGroup',
            title: '采购组',
            width: 100,
            exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
            }
        },
        {
            field: 'voucherType',
            title: '凭证类型',
            width: 100,
            exportEnum:[
                {code:1,codeWithDesc:'材料'},
                {code:2,codeWithDesc:'寄售'},
                {code:3,codeWithDesc:'其他'}
            ],
            formatter: function (value) {
                if (value===1){
                    return '材料';
                }else if (value===2){
                    return '寄售';
                }else {
                    return '其他';
                }
            }
        },
        {
            field: 'taxCode',
            title: '税率',
            width: 100,
            exportEnum:getNecessaryDataList('pc/sys/tax/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
            }
        },
        {
            field: 'paymentTermCode',
            title: '付款条件',
            width: 100,
            exportEnum:getDictList('payment_method'),
            formatter: function (value) {
                return getDicName('payment_method',value);
            }
        },
        {
            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: 'updateTime',
            title: '最后更新时间',
            width: 140,
            sortable: true,
            exportDateFormatter:'dateTime',
            formatter: function (value) {
                if (!value) {
                    return '';
                }
                return moment(value).format('YYYY-MM-DD HH:mm');
            }
        },
        {
            field: 'deleteFlag',
            title: '删除标记',
            width: 80,
            sortable: true,
            exportEnum:[
                {code:0,codeWithDesc:'未删除'},
                {code:1,codeWithDesc:'已删除'}
            ],
            formatter:function (value) {
                if(value === 0){
                    return "未删除"
                }else{
                    return "<span style='color: red;'>已删除</span>"
                }
            }
        },
        {
            field: 'paymentStatus',
            title: '付款状态',
            width: 80
        },
        {
            field: 'paymentRemark',
            title: '付款备注',
            width: 120,
            editor: {type: 'textbox', options: {editable: true}}
        },
        {
            field: 'supplierName2',
            title: '报关公司',
            width: 120,
            sortable: true
        },
        {
            field: 'remark',
            title: '备注',
            width: 120,
            sortable: true
        },
        {
            field: 'salesAgreementSignStatus',
            title: '购销合同签署状态',
            width: 115,
            sortable: true,
            exportEnum:[
                {code:0,codeWithDesc:'草稿'},
                {code:1,codeWithDesc:'签署中'},
                {code:2,codeWithDesc:'完成'},
                {code:3,codeWithDesc:'已过期'},
                {code:4,codeWithDesc:'已拒签'},
                {code:5,codeWithDesc:'已作废'},
                {code:6,codeWithDesc:'作废中'}
            ],
            formatter: function (value) {
                switch (value) {
                    case 0:
                        return '<span style="color: grey;">草稿</span>';
                    case 1:
                        return '<span style="color: blue;">签署中</span>';
                    case 2:
                        return '<span style="color: green;">完成</span>';
                    case 3:
                        return '<span style="color: orange;">已过期</span>';
                    case 4:
                        return '<span style="color: red;">已拒签</span>';
                    case 5:
                        return '<span style="color: dimgrey;">已作废</span>';
                    case 6:
                        return '<span style="color: blue;">作废中</span>';
                    default:
                        return '';
                }
            }
        }
        // {
        //     field: 'purchaseUser',
        //     title: '采购员',
        //     width: 150,
        // }
    ];
    //供应商不能看到的字段
    if (Number($(el.isSupplier).val())===1){
        el.defaultColumns = el.defaultColumns.filter(obj => obj.field !== 'paymentExpireDate');
    }
    //从后台查询动态列
    let column = getRemoteColumnSort(columnSortCodeEnum.ACCOUNT_STATEMENT_SUP,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:待推送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.paymentStatus).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            // 数据状态 0:否 1:是
            {label: '全部', value: -1},
            {label: '是', value: 1},
            {label: '否', value: 2}
        ],
        editable: false,
        panelHeight: 'auto'
    });

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

    $(el.paymentWay).combobox({
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way'
    });

    $(el.currencyCode).combobox({
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency'
    });


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

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

    $('#accountStatementMonth').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/account/statement/rest/sup/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            orderType: $(el.orderType).val()
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
            ]
        ],
        columns: [column],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    detail(2,0);
                }
            },
            '-',
            {
                text: '新增',
                iconCls: 'icon-add',
                id: 'btn_add',
                handler: function () {
                    detail(0,0);
                }
            },
            '-',
            {
                text: '编辑',
                iconCls: 'icon-edit',
                id: 'btn_edit',
                handler: function () {
                    detail(1,0);
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_del',
                handler: function () {
                    delStatementOrder();
                }
            },
            '-',
            {
                text: '提交确认',
                iconCls: 'icon-ok',
                id: 'btn_submit',
                handler: function () {
                    submitConfirm();
                }
            },
            '-',
            {
                text: '打印',
                iconCls: 'icon-download',
                id: 'btn_print_download',
                handler: function () {
                    printInvoice();
                }
            },
            '-',
            {
                text: '线下盖章附件上传',
                iconCls: 'icon-redo',
                id: 'btn-file-sign',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    //如果为发票已确认状态，不可发起线下盖章附件上传。
                    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: g.ctx + 'pc/finance/invoiced/apply/rest/checkApply?accountStatementNo=' + row.accountStatementNo + '&type=1'+'&accountStatementId='+row.id,
                        type: 'GET',
                        processData: false,
                        contentType: false,
                        success: function () {
                            $("#fileUpload .filebox-label").click();
                        },
                        complete: function(data) {
                            top.layer.close(loading);
                        },
                        error: function (data) {
                            parent.layer.alert("该对账单为发票已确认状态，不可发起线下盖章附件上传操作!",{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            '-',
            {
                text: '电子印章签署',
                iconCls: 'icon-sign',
                id: 'btn-sign',
                handler: function () {
                    sendSign();
                    setOperationLog("电子印章签署", "订单对账");

                }
            },
            '-',
            {
                text: '查看签署文件',
                iconCls: 'icon-find',
                id: 'btn-sign-look',
                handler: function () {
                    signFileLook();
                }
            },
            '-',
            {
                text: '列表导出',
                iconCls: 'icon-redo',
                id: 'btn_list_export',
                handler: function () {
                    openExportDialog('pc/finance/account/statement/rest/sup/export','tb', getQuery());
                }
            },"-",
            {
                text: '列设置',
                iconCls: 'icon-anchor',
                id: 'btn_column_sort',
                handler: function () {
                    openSortDialog({
                        //唯一编码
                        code: columnSortCodeEnum.ACCOUNT_STATEMENT_SUP,
                        //初始列（每次新增或删除列需要手动删除sys_column_sort表中对应code数据）
                        columns: el.defaultColumns,
                        callBack : function (newColumns) {
                            loadGrid(newColumns);
                        },
                    });
                }
            },
            '-',
            {
                text: '购销合同签署',
                iconCls: 'icon-sign',
                id: 'btn-gx-sign',
                handler: function () {
                    sendGxSign();
                    setOperationLog("购销合同签署", "订单对账");

                }
            },
            '-',
            {
                text: '购销合同查看',
                iconCls: 'icon-find',
                id: 'btn-sign-gx-look',
                handler: function () {
                    signGxFileLook();
                    setOperationLog("购销合同查看", "订单对账");

                }
            },
            '-',
            {
                text: '线下购销合同上传',
                iconCls: 'icon-redo',
                id: 'btn-file-gx-sign',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    //如果为发票已确认状态，不可发起线下盖章附件上传。
                    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: g.ctx + 'pc/finance/invoiced/apply/rest/checkApply1?accountStatementNo=' + row.accountStatementNo + '&type=1'+'&accountStatementId='+row.id,
                        type: 'GET',
                        processData: false,
                        contentType: false,
                        success: function () {
                            var url = g.ctx + 'pc/finance/account/statement/contractFileUpload?id='+row.id;
                            el.contractFileUpload = openDialog('contractFileUpload', url, {
                                title: '线下购销合同上传',
                                width: '500',
                                height: '450',
                                cache: false,
                                modal: true,
                                border: 'thin',
                                onClose: function () {
                                    el.contractFileUpload.dialog('destroy');
                                },
                                buttons: [
                                    {
                                        text: '保存',
                                        iconCls: 'icon-save',
                                        handler: function () {
                                            topWin.frames['contractFileUpload'].confirm(function (param) {
                                                var formData = new FormData()
                                                formData.append("signFile",param.files)
                                                formData.append("businessTypeCode",param.businessTypeCode)
                                                formData.append("id",row.id)
                                                var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                                                $.ajax({
                                                    url: g.ctx + 'pc/finance/account/statement/rest/saveSignFile1',
                                                    type: 'POST',
                                                    data: formData,
                                                    processData: false,
                                                    contentType: false,
                                                    success: function () {
                                                        el.contractFileUpload.dialog('close');
                                                        topWin.layer.msg('上传成功', {icon: 1});
                                                        $(el.tb).datagrid('reload');
                                                    },
                                                    complete: function(data) {
                                                        top.layer.close(loading);
                                                    },
                                                    error: function (data) {
                                                        parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                                                    }
                                                });
                                            });
                                        }
                                    },
                                    {
                                        text: '取消',
                                        iconCls: 'icon-cancel',
                                        handler: function () {
                                            el.contractFileUpload.dialog('close');
                                        }
                                    }
                                ]
                            });
                            // $("#fileUpload1 .filebox-label").click();
                        },
                        complete: function(data) {
                            top.layer.close(loading);
                        },
                        error: function (data) {
                            parent.layer.alert("该对账单为发票已确认状态，不可发起线下盖章附件上传操作!",{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                }
            },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportStatementOrder();
            //     }
            // }
        ],
        onClickCell: function (index, field, value) {
             var ed;
             if (field == "paymentRemark") {//依次判断当前编辑的是哪一列
                 if (_flag) {//如果上一次编辑状态未结束，先结束上一次编辑
                     $(this).datagrid('endEdit', _index);//结束编辑
                 }
                 $(this).datagrid('beginEdit', index);//开始本次编辑
                 ed = $(this).datagrid('getEditor', { index: index, field: field });
                 $(ed.target).focus();
                 _index = index;  //记录本次编辑的行号
                 _flag = true;    //将编辑状态设置为true
             } else if (_flag) {
                 $(this).datagrid('endEdit', _index);
            }
        },
        onAfterEdit: function (rowIndex, rowData, changes) {
            //结束编辑后记录编辑数据
            _flag = false;
            if (changes && undefined != changes.paymentRemark) {
            } else {
                return;
            }
            //el.editData[rowData.id] = rowData;
            $.ajax({
                url: g.ctx + 'pc/finance/account/statement/rest/savePaymentRemark',
                data: {id: rowData.id, paymentRemark: changes.paymentRemark},
                // data: {ids: JSON.stringify(ids),type:0},
                // data: JSON.stringify(postData),
                // contentType: 'application/json',
                type: 'POST',
                complete: function () {
                    //topWin.layer.close(loadingIndex);
                },
                success: function () {

                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });

        },
        onLoadSuccess: function () {
            //displayButtonByUserRole('fin.account.statement.material.index');
            $(el.tb).datagrid('clearSelections');
            reloadOk = true;
        },
        onBeforeLoad: function (param) {
            displayButtonByUserRole('fin.account.statement.material.index');
            reloadOk = false;
        },
        onCheck: function (index, row) {
            // 对账单数据状态 1:暂存对账单 2:待确认 3:采购拒绝对账单 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认对账单 8:财务驳回对账单 9:对账单已确认
            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');

            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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                    btn.eq(13).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');
                        btn.eq(13).linkbutton('enable');
                    // }
                    break;
                default:
                    break;
            }

            // switch (Number(signFileStatus)){
            //     case 0:
            //         btn.eq(6).linkbutton('disable');
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 1:
            //         btn.eq(6).linkbutton('enable');
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 2:
            //         btn.eq(6).linkbutton('disable');
            //         btn.eq(7).linkbutton('enable');
            //         break;
            // }

            // switch (Number(signStatus)){
            //     case 1:
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 3:
            //         btn.eq(7).linkbutton('enable');
            //         break;
            //     case 4:
            //         btn.eq(7).linkbutton('enable');
            //         break;
            // }
            if (row.deleteFlag!==0){
                btn.eq(4).linkbutton('disable');
            }
        },
        onClickRow: function (index, row) {
            // 对账单数据状态 1:暂存对账单 2:待确认 3:采购拒绝对账单 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认对账单 8:财务驳回对账单 9:对账单已确认
            var status = row.status;
            var signFileStatus = row.signFileStatus;
            var signStatus = row.signStatus;
            // 按钮 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;
            }

            // switch (Number(signFileStatus)){
            //     case 0:
            //         btn.eq(6).linkbutton('disable');
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 1:
            //         btn.eq(6).linkbutton('enable');
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 2:
            //         btn.eq(6).linkbutton('disable');
            //         btn.eq(7).linkbutton('enable');
            //         break;
            // }
            //
            // switch (Number(signStatus)){
            //     case 1:
            //         btn.eq(7).linkbutton('disable');
            //         break;
            //     case 3:
            //         btn.eq(7).linkbutton('enable');
            //         break;
            //     case 4:
            //         btn.eq(7).linkbutton('enable');
            //         break;
            // }
            if (row.deleteFlag!==0){
                btn.eq(4).linkbutton('disable');
            }
        }
    });
}


/**
 * 查看对账单
 */
function lookStatementOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }
    setOperationLog("查看按钮", "订单对账首页");
    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');
                }
            }
        ]
    });
}


function padZero(num) {
    return num < 10 ? '0' + num : num;
}
/**
 * 新增对账单
 * optType 操作类型；0-新增；1-编辑；2-查看；3-主管确认；4-财务确认
 * optMenu 操作菜单；0-订单对账；1-采购对账；2-财务对账
 */
function detail(optType,optMenu) {

    // 限制新增对账标识 0:不限制 1:限制
    if(Number($(el.restrictFlag).val()) === 1) {
        topWin.layer.alert('本阶段系统限制了您不能创建对账单, 如有疑问请联系对应采购', {icon: 0});
        return false;
    }
    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?orderType=' + $(el.orderType).val()+'&id='+id+'&optType='+optType+'&optMenu='+optMenu;
    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');
                }
            }
        );
    }
    setOperationLog( optType===0?'新增对账单':optType===1?'编辑对账单':optType===2?'查看对账单':optType===3?'采购确认对账单':'财务确认对账单', "对账单");
    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 editStatementOrder() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }

    if(Number(row.status) === 1 || Number(row.status) === 3 || Number(row.status) === 8){
        var url = g.ctx + 'fin/account/statement/edit?id=' + row.id;
        el.addOrEditDialog = openDialog('editStatementOrder', url, {
            title: '编辑对账单',
            width: '99%',
            height: '100%',
            cache: false,
            modal: true,
            border: 'thin',
            onClose: function () {
                el.addOrEditDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: '暂存',
                    iconCls: 'icon-save',
                    handler: function () {
                        topWin.frames['editStatementOrder'].dataSave(0,function () {
                            topWin.layer.msg('数据保存成功', {icon: 1});
                            $(el.tb).datagrid('load');
                            el.addOrEditDialog.dialog('close');
                        });
                    }
                },
                // {
                //     text: '提交',
                //     iconCls: 'icon-ok',
                //     handler: function () {
                //         topWin.frames['editStatementOrder'].dataSave(1,function (statementId) {
                //             $(el.tb).datagrid('load');
                //             el.addOrEditDialog.dialog('close');
                //             dataSaveSubmit(statementId);
                //             // topWin.layer.confirm('对账单已保存成功！您确定要提交至采购确认吗?', {icon: 3}, function (index) {
                //             //     topWin.layer.close(index);
                //             //
                //             // });
                //         });
                //     }
                // },
                {
                    text: '取消',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        $(el.tb).datagrid('reload');
                        el.addOrEditDialog.dialog('close');
                    }
                }
            ]
        });
    }else {
        topWin.layer.alert('只能编辑暂存或采购拒绝状态或财务拒绝的对账单', {icon: 0});
        return false;
    }
}


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

    var ids = [];
    if(Number(row.status) === 1 || Number(row.status) === 3 || Number(row.status) === 8){
        ids.push(row.id);
    }else {
        topWin.layer.alert('对账单号: ' + row.accountStatementNo + ', 不可以删除', {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/del',
            type: 'POST',
            data: {ids: JSON.stringify(ids),type:0},
            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(data.responseJSON.message, {icon: 2});
            }
        });
    });
}

//打印
function printInvoice() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert("请选择数据", {icon: 0});
        return false;
    }
    if(row.deleteFlag === 1){ layer.msg("删除的单据不可打印"); return; }

    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/finance/account/statement/print?id=' + row.id,
        success: function (data) {
            $('#printOrder').print({
                globalStyles: false,
                mediaPrint: true,
                iframe: true,
                prepend: data,
                deferred: $.Deferred().done(function () {
                    // $.ajax({
                    //     type: 'POST',
                    //     url: g.ctx + 'pc/finance/invoiced/apply/rest/update/print?id=' + row.id,
                    //     success: function (data) {
                    //         $('#tb').datagrid('reload');
                    //     }
                    // });
                })
            });
        }
    });
}

/**
 * 列表上提交确认
 */
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);


            // var url = g.ctx + '/fin/account/statement/purchase/index';
            // openOptConfirmDialog(1, url, '采购确认对账单');
            // refreshFramesDatagrid("/fin/account/statement/purchase/index");
            // if(0 === Number($(el.isSupplier).val())){
            //     var url = g.ctx + 'fin/account/statement/opt/confirm?id=' + statementId + '&roleType=1';
            //     openOptConfirmDialog(1, url, '采购确认对账单');
            // }else {
            //     topWin.layer.msg('数据保存成功', {icon: 1});
            //     $(el.tb).datagrid('load');
            // }

        },
        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();
    debugger;
    $(el.tb).datagrid('load');
}

function getQuery() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.statementNo = $.trim($(el.statementNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    // queryParams.oaProcessNo = $.trim($(el.oaProcessNo).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.status = $(el.status).combobox('getValue');
    queryParams.isComplete = $(el.isComplete).combobox('getValue');
    queryParams.paymentStatus = $(el.paymentStatus).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.orderType = $(el.orderType).val();
    queryParams.createUserName = $('#createUserName').textbox('getValue');
    queryParams.accountStatementMonth = $(el.accountStatementMonth).val();
    queryParams.accountStatementYear = $(el.accountStatementYear).val();
    queryParams.paymentWay = $(el.paymentWay).combobox('getValue');
    queryParams.currencyCode = $(el.currencyCode).combobox('getValue');
    return queryParams;
}


/**
 * 重置查询
 */
function resetAsSearch() {
    $(el.statementNo).val('');
    $(el.supCodeOrName).val('');
    // $(el.oaProcessNo).val('');
    $(el.statementNo).val('');
    $(el.statementNo).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.purchaseGroup).combobox('setValue', '');
    $(el.status).combobox('setValue', -1);
    $(el.isComplete).combobox('setValue', -1);
    $(el.paymentStatus).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $('#createUserName').textbox('setValue', '');
    $(el.accountStatementYear).val('');
    $(el.accountStatementMonth).combobox('setValue', "");
    $(el.paymentWay).combobox('setValue', '');
    $(el.currencyCode).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');
                }
            }
        ]
    });
}

$("#fileInput").filebox({
    buttonText: 'Choose', buttonAlign: 'left', onChange: function () {
        let row = $(el.tb).datagrid("getSelected");
        let addFiles = [];
        let files = $("#fileInput").filebox('files'), formData = new FormData()
        for (let r = 0; r < files.length; r++) {
            addFiles.push(files[r]);
        }
        for (let n = 0; n < addFiles.length; n++) {
            formData.append('files', addFiles[n]);
        }
        if (addFiles.length > 0) {
            fileUploadAjaxWithCall(formData, function (rows) {
                const postData = []
                $.each(rows, function (idx, itm) {
                    postData.push({
                        fileId: itm.id, accountStatementId: row.id
                    })
                })
                formData.append("signFile",postData[0].fileId)
                formData.append("id",postData[0].accountStatementId)
                var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                $.ajax({
                    url: g.ctx + 'pc/finance/account/statement/rest/saveSignFile',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {
                        topWin.layer.msg('上传成功', {icon: 1});
                        $(el.tb).datagrid('reload');
                    },
                    complete: function(data) {
                        top.layer.close(loading);
                    },
                    error: function (data) {
                        parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                    }
                });
            }, true)
            $("#fileInput").filebox('clear')
        }
    }
});
$("#fileInput1").filebox({
    buttonText: 'Choose', buttonAlign: 'left', onChange: function () {
        let row = $(el.tb).datagrid("getSelected");
        let addFiles = [];
        let files = $("#fileInput1").filebox('files'), formData = new FormData()
        for (let r = 0; r < files.length; r++) {
            addFiles.push(files[r]);
        }
        for (let n = 0; n < addFiles.length; n++) {
            formData.append('files', addFiles[n]);
        }
        if (addFiles.length > 0) {
            fileUploadAjaxWithCall(formData, function (rows) {
                const postData = []
                $.each(rows, function (idx, itm) {
                    postData.push({
                        fileId: itm.id, accountStatementId: row.id
                    })
                })
                formData.append("signFile",postData[0].fileId)
                formData.append("id",postData[0].accountStatementId)
                var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                $.ajax({
                    url: g.ctx + 'pc/finance/account/statement/rest/saveSignFile1',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {
                        topWin.layer.msg('上传成功', {icon: 1});
                        $(el.tb).datagrid('reload');
                    },
                    complete: function(data) {
                        top.layer.close(loading);
                    },
                    error: function (data) {
                        parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                    }
                });
            }, true)
            $("#fileInput1").filebox('clear')
        }
    }
});

function sendSign() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    //电子印章签署 先根据对账单号 查询申请单中，是否存在且状态为发票已确认状态 select * from fin_invoiced_apply fia  where  account_statement_no = '24000091'
    //  and status = 9 如果存在则提示该单已经为发票已确认状态，不可发起电子印章签署操作。
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/invoiced/apply/rest/checkApply?accountStatementNo=' + row.accountStatementNo + '&type=1'+'&accountStatementId='+row.id,
        type: 'GET',
        processData: false,
        contentType: false,
        success: function (result) {
            openSignDialog('esignDialog',{
                //业务类型编码
                title:'对账单'+row.accountStatementNo,
                //业务类型编码
                businessTypeCode:eSignBusinessTypeCodeEnum.ACCOUNT_STATEMENT,
                //业务唯一id
                businessId:row.id,
                //甲方
                firstParty:row.companyCode,
                //甲方默认用户id
                firstPartyUserId:row.financeConfirmUserId,
                //甲方名称
                firstPartyName:getNecessaryDataName('pc/sys/company/rest/listAll',row.companyCode),
                //乙方
                secondParty:row.supplierCode,
                //乙方名称
                secondPartyName:row.supplierName,
                sumSignFlag:1,
                summaryFileId : "",
                callBack : function () {
                    $(el.tb).datagrid('reload');
                },
            });
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

function signFileLook() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    openSignLookDialog('esignDialog',row.id,eSignBusinessTypeCodeEnum.ACCOUNT_STATEMENT);
}

//2024-09-05
function sendGxSign() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录");
        return;
    }
    var status = row.status;
    var paymentWay = row.paymentWay;
    // if(!(Number(status) == 9 && paymentWay =="C")){
    //     topWin.layer.msg("只有数据状态为对账单已确认且付款方式为承兑汇票的对账单可以进行电子签署！");
    //     return;
    // }
    if(!(Number(status) == 9)){
        topWin.layer.msg("只有数据状态为对账单已确认的对账单可以进行电子签署！");
        return;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/invoiced/apply/rest/checkApply1?accountStatementNo=' + row.accountStatementNo + '&type=1'+'&accountStatementId='+row.id,
        type: 'GET',
        processData: false,
        contentType: false,
        success: function (result) {

            openSignDialog('esignDialog', {
                //业务类型编码
                title: '购销合同'+row.accountStatementNo,
                //业务类型编码
                businessTypeCode: eSignBusinessTypeCodeEnum.PURCHASE_SALE_CONTRACT,
                //业务唯一id
                businessId:row.id,
                //甲方
                firstParty:row.companyCode,
                //甲方默认用户id
                firstPartyUserId:row.financeConfirmUserId,
                //甲方名称
                firstPartyName:getNecessaryDataName('pc/sys/company/rest/listAll',row.companyCode),
                //乙方
                secondParty:row.supplierCode,
                //乙方名称
                secondPartyName:row.supplierName,
                sumSignFlag:1,
                summaryFileId :"",
                callBack: function () {
                    debugger
                    //设置补录状态
                    $.ajax({
                        url: g.ctx + 'pc/finance/invoiced/apply/rest/setContractSupplementStatus',
                        type: 'POST',
                        data: {accountStatementNo: row.accountStatementNo,contractSupplementFlag:result.data?0:1},
                        success: function () {
                            $(el.tb).datagrid('reload');
                        },
                        error: function (data) {
                            topWin.layer.close(loading);
                            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                },
            });
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

function signGxFileLook() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    openSignLookDialog('esignDialog',row.id,eSignBusinessTypeCodeEnum.PURCHASE_SALE_CONTRACT+','+eSignBusinessTypeCodeEnum.PURCHASE_SALE_PROCESS_CONTRACT);
}