/**
 * 对账模块-财务对账确认首页JS
 *
 * Created by li.kui on 2020/8/28.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    userId: '#userId',
    companyCode: '#companyCode',
    purchaseGroup: '#purchaseGroup',
    supCodeOrName: '#supCodeOrName',
    statementNo: '#statementNo',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    status: '#status',
    orderType: '#orderType',
    oaProcessNo: '#oaProcessNo',
    tb: '#tb',
    addOrEditDialog: null,
    optConfirmDialog: null,
    forceDelDialog: null,
    lookDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


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

    loadGrid();
});


/**
 * 初始化页面下拉框数据
 */
function initComBoBoxData() {
    //2-待主管确认、3-主管拒绝对账单，7-待采购确认，8-采购拒绝对账单，9-对账单已确认
    // 初始化状态下拉框
    // 对账单数据状态 1:暂存对账单 2:待确认 3:采购拒绝对账单 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认对账单 8:财务驳回对账单 9:对账单已确认
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        value: 7,
        data: [
            {label: '全部', value: -1},
            {label: '待财务确认', value: 7},
            {label: '对账单已确认', value: 9}
        ],
        editable: false,
        panelHeight: 'auto',
    });

    // 初始化对账单类型下拉框
    $(el.orderType).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            {label: '全部', value: -1},
            {label: '材料类', value: 1},
            {label: '运费类', value: 2}
        ],
        editable: false,
        panelHeight: 'auto'
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll?userId='+$(el.userId).val(),
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });

    //初始化日期
    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'
    });
}


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

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        emptyMsg: '暂无数据',
        url: g.ctx + 'pc/finance/account/statement/rest/list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: true,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        queryParams: {
            roleType: 2,
            status: 7
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'status',
                    title: '数据状态',
                    width: 110,
                    sortable: true,
                    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: 'accountStatementNo',
                    title: '对账单号',
                    width: 80,
                    sortable: true
                }
            ]
        ],
        columns: [
            [

                {
                    field: 'accountStatementYear',
                    title: '对账单年份',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'accountStatementMonth',
                    title: '对账单月份',
                    width: 100,
                    sortable: true
                },

                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270,
                    sortable: true
                },
                {
                    field: 'notTaxAmount',
                    title: '对账未税总金额',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxAmount',
                    title: '对账含税总金额',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'diffTaxAmount',
                    title: '对账总税额',
                    width: 110,
                    sortable: true,
                    formatter: function (value, row) {
                        return formatNumber(Number(row.taxAmount) - Number(row.notTaxAmount), 2, 1);
                    }
                },
                // {
                //     field: 'currPaymentAmount',
                //     title: '本期付款金额',
                //     width: 110,
                //     sortable: true,
                //     formatter: function (value, row) {
                //         if (!value) {
                //             return '0.00';
                //         }
                //         return formatNumber(row.currPaymentAmount, 2, 1);
                //     }
                // },
                {
                    field: 'invoiceCompleteFlag',
                    title: '是否开票',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (Number(value) === 0) {
                            return '否';
                        }
                        return '<span style="color: green;">是</span>';
                    }
                },
                {
                    field: 'paymentWay',
                    title: '付款方式',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        return getDicName('payment_way',value);
                    }
                },
                {
                    field: 'companyCode',
                    title: '采购公司',
                    width: 240,
                    formatter: function (value, row) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 100,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                    }
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'updateTime',
                    title: '最后更新时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
                {
                    field: 'remark',
                    title: '备注',
                    width: 120,
                    sortable: true
                },
                // {
                //     field: 'purchaseUser',
                //     title: '采购员',
                //     width: 140,
                // }
            ]
        ],
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-find',
                id: 'btn_look',
                handler: function () {
                    detail(2,2);
                }
            },
            '-',
            {
                text: '财务确认',
                iconCls: 'icon-ok',
                id: 'btn_finance_confirm',
                handler: function () {
                    detail(4,2);
                    setOperationLog("财务确认按钮", "财务对账确认");

                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_del',
                handler: function () {
                    delStatementOrder();
                }
            },
            '-',
            {
                text: '财务撤销',
                iconCls: 'icon-redo',
                id: 'btn_revoke_fc',
                handler: function () {
                    revokeFinConfirmed();
                }
            },
            '-',
            {
                text: '查看影像',
                iconCls: 'icon-find',
                id: 'btn_look_img',
                handler: function () {
                    var row = $(el.tb).edatagrid('getSelected');
                    if (!row) {
                        topWin.layer.alert('请选择一条开票申请单进行操作', {icon: 0});
                        return false;
                    }
                    const imageCode = row.imgCode;
                    if (!imageCode) {
                        topWin.layer.alert("请先推送影像", {icon: 2, title: "温馨提示"});
                    } else {
                        $.ajax({
                            type: 'get',
                            url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
                            data: {
                                imageCode: imageCode
                            },
                            success: function (data) {
                                if (data) {
                                    window.open(data, "_blank");
                                }
                            },
                            error: function (error) {
                                topWin.layer.alert(error.responseJSON.message, {
                                    icon: 2,
                                    content: error.responseJSON.message
                                });
                            }
                        });
                    }
                }
            },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportStatementOrder();
            //     }
            // }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole('fin.account.statement.finance.index');
            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (index, row) {
            // 对账单数据状态 7:待财务确认对账单 9:对账单已确认
            var status = row.status;
            // 按钮 0:查看 1:财务确认 2:导出
            var btn = $('div.datagrid-toolbar a');
            switch (Number(status)){
                case 7:
                    $('#btn_finance_confirm').linkbutton('enable');
                    $('#btn_revoke_fc').linkbutton('disable');
                    break;
                case 9:
                    $('#btn_finance_confirm').linkbutton('disable');
                    $('#btn_revoke_fc').linkbutton('enable');
                    break;
                default:
                    $('#btn_finance_confirm').linkbutton('disable');
                    break;
            }
        },
        onClickRow: function (index, row) {
            // 对账单数据状态 7:待财务确认对账单 9:对账单已确认
            var status = row.status;
            // 按钮 0:查看 1:财务确认 4:导出
            var btn = $('div.datagrid-toolbar a');
            switch (Number(status)){
                case 7:
                    btn.eq(1).linkbutton('enable');
                    break;
                default:
                    btn.eq(1).linkbutton('disable');
                    break;
            }
        }
    });
}
/**
 * 撤销财务已确认
 */
function revokeFinConfirmed() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }
    if(Number(row.status) !== 9){
        topWin.layer.alert('只有财务已确认对账单状态的才能撤销', {icon: 0});
        return false;
    }

    topWin.layer.prompt({title: '请填写撤销原因', formType: 2, maxlength: 255}, function (text, index) {
        var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/account/statement/rest/revoke/fin/confirmed',
            type: 'POST',
            data: {
                asId: row.id,
                revokeReason: text
            },
            success: function () {
                topWin.layer.close(index);
                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: '温馨提示'});
            }
        });
    });
}

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

    var url = g.ctx + 'fin/account/statement/look?id=' + row.id;
    el.lookDialog = openDialog('lookStatementOrder', url, {
        title: '查看对账单',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.lookDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.lookDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 新增对账单
 * optType 操作类型；0-新增；1-编辑；2-查看；3-主管确认；4-财务确认
 * optMenu 操作菜单；0-订单对账；1-采购对账；2-财务对账
 */
function detail(optType, optMenu) {
    var id = '';
    if (optType!==0){
        var row = $(el.tb).datagrid('getSelected'), userId = $(el.userId).val();
        if (!row) {
            topWin.layer.alert('请选中一条记录', {icon: 0});
            return false;
        }
        id = row.id;
    }

    var url = g.ctx + 'pc/finance/account/statement/detail?id='+id+'&optType='+optType+'&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');
                }
            }
        );
    }else if (optType===3){
        buttons.push(
            {
                text: '通过',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['addStatementOrder'].purchaseSave(function (data) {
                        purchaseApprove(1, data);
                    });
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['addStatementOrder'].purchaseRefuseStatement(function (data) {
                        purchaseApprove(0, data);
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }else if (optType===4){
        buttons.push(
            {
                text: '通过',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['addStatementOrder'].financeSave(function (data) {
                        financeApprove(1, data);
                    },1);
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['addStatementOrder'].purchaseRefuseStatement(function (data) {
                        financeApprove(0, data);
                    },0);
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    el.addOrEditDialog.dialog('close');
                }
            }
        );
    }
    el.addOrEditDialog = openDialog('addStatementOrder', url, {
        title: optType===0?'新增对账单':optType===1?'编辑对账单':optType===2?'查看对账单':optType===3?'采购确认对账单':'财务确认对账单',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addOrEditDialog.dialog('destroy');
        },
        buttons: buttons
    });
}

/**
 * 删除对账单
 */
function 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 || Number(row.status) === 9){
        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 optConfirm() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }
    var status = row.status, id = row.id;
    var url = g.ctx + 'fin/account/statement/opt/confirm?id=' + id + '&roleType=2';
    if(Number(status) === 7){
        el.optConfirmDialog = openDialog('optConfirm', url, {
            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'].financeSave(function (data) {
                            financeApprove(1, data);
                        });
                    }
                },
                {
                    text: '拒绝',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        topWin.frames['optConfirm'].financeSave(function (data) {
                            financeApprove(0, data);
                        });
                    }
                },
                {
                    text: '关闭',
                    iconCls: 'icon-clear',
                    handler: function () {
                        el.optConfirmDialog.dialog('close');
                    }
                }
            ]
        });
    }else {
        topWin.layer.alert('财务只能操作待财务确认状态的对账单', {icon: 0});
        return false;
    }
}


/**
 * 财务审批
 *
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param submitData 提交数据
 */
function financeApprove(approveStatus, submitData) {
    submitData.roleType = 2;
    submitData.approveStatus = approveStatus;

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

            topWin.layer.msg('操作成功', {icon: 1});
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


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

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


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


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