var el = {
    searchForm: '#searchForm',
    tb: '#tb',
    purchaseGroup: '#purchaseGroup',
    paymentWay: '#paymentWay',
    status: '#status',
    postStatus: '#postStatus',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    type: '#type',
    cost_matching_add: '#cost_matching_add',
    cost_matching_edit: '#cost_matching_edit',
    cost_matching_search: '#cost_matching_search',
    cost_matching_push_confirm: '#cost_matching_push_confirm',
    btn_remove: '#btn_remove',
    defaultColumns: [],
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    initDict('unit,currency,payment_way,payment_method')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/company/rest/listAll');
    initCombo();
    loadGrid();
});

function initCombo(){
    $(el.status).combobox({
        valueField: 'value',
        textField: 'label',
        value: 7,
        data: [
            {label: '待财务确认', value: 7},
            {label: '对账单已确认', value: 9}
        ],
        editable: false,
        panelHeight: 'auto'
    });
    $(el.postStatus).combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        prompt: '--- 请选择 ---',
        data: [
            {label: '未过账', value: 1},
            {label: '预制失败', value: 3},
            {label: '预制成功', value: 4},
            {label: '过账成功', value: 5}
        ],
    });

    $(el.accountStatementYear).combobox({
        required: false,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': moment().format('YYYY'), 'code': moment().format('YYYY')},
            {'name': moment().add(-12, 'month').format('YYYY'), 'code': moment().add(-12, 'month').format('YYYY')},
            {'name': moment().add(-24, 'month').format('YYYY'), 'code': moment().add(-24, 'month').format('YYYY')},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    $(el.accountStatementMonth).combobox({
        required: false,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '01', 'code': '01'},
            {'name': '02', 'code': '02'},
            {'name': '03', 'code': '03'},
            {'name': '04', 'code': '04'},
            {'name': '05', 'code': '05'},
            {'name': '06', 'code': '06'},
            {'name': '07', 'code': '07'},
            {'name': '08', 'code': '08'},
            {'name': '09', 'code': '09'},
            {'name': '10', 'code': '10'},
            {'name': '11', 'code': '11'},
            {'name': '12', 'code': '12'},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    $(el.purchaseGroup).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll')
    });
    // 付款方式
    $(el.paymentWay).combobox({
        required: false,
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way'
    });
}


function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight - 20, 37, 40);
    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        url: g.ctx + 'pc/finance/company/account/statement/rest/list?statusListStr=7,9',
        singleSelect: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        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: '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,
                // }
            ]
        ],
        queryParams: {
            roleType: 1,
            status: $(el.status).combobox('getValue')
        },
        toolbar: [
            {
                text: '查看',
                iconCls: 'icon-search',
                id:'btn_look',
                handler: function () {
                    detail(2);
                }
            },
            '-',
            {
                text: '财务确认',
                iconCls: 'icon-ok',
                id: 'btn_finance_confirm',
                handler: function () {
                    detail(5);
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_del',
                handler: function () {
                    delStatementOrder();
                }
            },
            '-',
            {
                text: '财务撤销',
                iconCls: 'icon-redo',
                id: 'btn_revoke_fc',
                handler: function () {
                    revokeFinConfirmed();
                }
            },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     id: 'btn_export',
            //     handler: function () {
            //         exportStatementOrder();
            //     }
            // }
        ],
        onBeforeLoad:function () {
            displayButtonByUserRole('cost_account_statement_finance_list');
            $(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 revokeFinConfirm() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选择一条对账单进行操作', {icon: 0});
        return false;
    }
    if(Number(row.status) !== 7){
        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/company/account/statement/rest/revoke/fin/confirm',
            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 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/company/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 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/company/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: '温馨提示'});
            }
        });
    });
}


