var App = function () {
    this.userGrid = $('#task-grid');
    this.data = {};
    this.selectedRow = [];
    this.AddDialog = new AddDialog(this);
    this.EditDialog = new EditDialog(this);

    this.Startup = function () {
        $('#manage').addClass('active');

        this.ReLayout();
        this.InitOrgList();
        this.InitDataGrid();
        
        this.AddDialog.Setup();
        this.EditDialog.Setup();

        $('#add-btn').on('click', this.OnAddButtonClick.bind(this));
        $('#edit-btn').on('click', this.onEditButtonClick.bind(this));
        $('#delete-btn').on('click', this.onDeleteButtonClick.bind(this));
        $('#query-btn').on('click', this.onQueryButtonClick.bind(this));
        $('#delete-dialog-close').on('click', this.CloseDeleteDialog.bind(this));
        $('#dialog-sure').on('click', this.OnSureOfDeleteButtonClick.bind(this));
        $('#dialog-cancel').on('click', this.CloseDeleteDialog.bind(this));
        $('#query-btn').trigger('click');

        window.onresize = this.ReLayout.bind(this);
    };

    this.ReLayout = function () {
        var width = $(window).width();
        var height = $(window).height();
        $('.manage-table, .manage-table .datagrid').width(width -247);
        $('.manage-table, .manage-table .datagrid').height(height - 109);
        this.formatLastColumn();
    };

    this.InitOrgList = function () {
        $.ajax({
            type: "POST",
            dataType: 'text',
            url: '/OrgManagement/Query',
            data: {
                page: 1,
                rows: 10000
            },
            success: function (result) {
                var data = JSON.parse(result).rows;
                var newData = data.splice(0, 0, { Id: 0, Name: '全部' });

                $('#org-list').combobox({
                    valueField: 'Id',
                    textField: 'Name',
                    editable: false,
                    panelHeight: 'auto',
                    panelMaxHeight: 190,
                    data: data
                });
                $('#org-list').combobox('setValue', 0);
            }.bind(this)
        });
    };

    this.InitDataGrid = function () {
        this.userGrid.datagrid({
            columns: [[
                { field: 'RealName', title: '姓名', align: 'center', width: 120 },
                { field: 'OrgName', title: '所属机构', align: 'left', width: 180 },
                { field: 'LoginName', title: '登录账户', align: 'left', width: 150 },
                //{ field: 'LoginPassWord', title: '登录密码', align: 'left', width: 120, formatter: this.formatPassword.bind(this) },
                { field: 'ComputeCount', title: '计算次数', align: 'center', width: 80 },
                { field: 'LastComputeTime', title: '最后计算时间', align: 'center', width: 160, formatter: this.formatLastComputeTime.bind(this) },
                { field: 'LoginCount', title: '登录次数', align: 'center', width: 80 },
                { field: 'LastLoginTime', title: '最后登录时间', align: 'center', width: 160, formatter: this.formatLastLoginTime.bind(this) },
                { field: 'CreateTime', title: '创建时间', align: 'center', width: 160, formatter: this.formatTime.bind(this) },
                { field: 'Null', title: '', align: 'left' }
            ]],
            striped: true,
            singleSelect: false,
            fit: true,
            scrollbarSize: 0,
            pagination: true,
            pageNumber: 1,
            pageSize: 50,
            pageList: [10, 20, 50, 100, 150, 200],
            onSelect: this.OnTaskSelected.bind(this),
            onUnselect: this.OnTaskUnselected.bind(this),
            onBeforeLoad: this.OnTableGridBeforeLoad.bind(this),
            onLoadSuccess: function (data) {
                if (data.total === 0) {
                    var body = $(this).data().datagrid.dc.body2;
                    body.addClass('null-data-body');
                    body.append('<div class="null-data"><span></span><p>暂无数据</p></div>');
                }
                this.formatLastColumn();
            }.bind(this)
        });
    };

    this.formatLastColumn = function () {
        var width = $('.container').width();
        var headerTable = $('.datagrid-header');
        var bodyTable = $('.datagrid-body');
        var headerTd = headerTable.find('td:last');
        headerTd.css('width', (width - 1093) + 'px');
        bodyTable.find('tr').find('td:last').css('width', (width - 1093) + 'px');
    };

    this.onQueryButtonClick = function () {
        var orgId = $('#org-list').combobox('getValue') === '' ? 0 : $('#org-list').combobox('getValue');
        this.ReLoadTableData(orgId);
    };

    this.ReLoadTableData = function (orgId) {
        this.userGrid.datagrid({
            method: "POST",
            url: '/UserManagement/Query',
            queryParams: {
                orgId: orgId
            }
        });
    };

    this.formatPassword = function (password) {
        var len = password.length - 2;
        var symbol = '';
        for (var i = 0; i < len; i++) {
            symbol += '*';
        }
        return password.substring(0, 1) + symbol + password.substring(password.length - 1);
    };

    this.formatTime = function (time) {
        return '<span>{0}</span>'.format(moment(time).format('YYYY/MM/DD HH:mm:ss'));
    };

    this.formatLastComputeTime = function (time) {
        var value = time === null ? '-' : moment(time).format('YYYY/MM/DD HH:mm:ss');
        return '<span>{0}</span>'.format(value);
    };

    this.formatLastLoginTime = function (time) {
        var value = time === null ? '-' : moment(time).format('YYYY/MM/DD HH:mm:ss');
        return '<span>{0}</span>'.format(value);
    }

    this.OnTaskSelected = function (index, row) {
        this.selectedRow = row;
        $('.datagrid-btable tr').removeClass('datagrid-row-selected');
        $('.datagrid-btable tr').eq(index).addClass('datagrid-row-selected');

        //set buttons disabled state
        $('#edit-btn').prop('disabled', row === null);
        $('#delete-btn').prop('disabled', row === null);
        $('#enable-btn').prop('disabled', row.isEnable !== 1 ? null : true);
        $('#disable-btn').prop('disabled', row.isEnable === 1 ? null : true);
    };

    this.OnTaskUnselected = function (index, row) {
        this.DisabledEvent();
    };

    this.OnTableGridBeforeLoad = function () {
        this.userGrid.datagrid('getPager').pagination({
            beforePageText: '第',
            afterPageText: '页&nbsp;&nbsp;&nbsp;共{pages}页',
            displayMsg: '当前显示{from}-{to}条记录&nbsp;&nbsp;&nbsp;共{total}条记录',
            layout: ['list', 'sep', 'first', 'prev', 'sep', 'manual', 'sep', 'next', 'last', 'sep', 'refresh', 'info']
        });

        
    };

    this.OnAddButtonClick = function () {
        this.AddDialog.Show();
    };

    this.onEditButtonClick = function () {
        this.EditDialog.Show(this.selectedRow);
    };

    this.onDeleteButtonClick = function () {
        $('.dialog-delete').show();
        $('.dialog-clear h2').text('确定删除名为「{0}」的用户吗?'.format(this.selectedRow.RealName));
    };

    this.OnSureOfDeleteButtonClick = function () {
        this.DeleteUser();
        this.CloseDeleteDialog();
        this.DisabledEvent();
    };

    this.CloseDeleteDialog = function () {
        $('.dialog-delete').hide();
    };

    this.DeleteUser = function () {
        $.ajax({
            type: "POST",
            dataType: 'text',
            url: '/UserManagement/Delete',
            data: {
                id: this.selectedRow.Id
            },
            success: function () {
                this.ReLoadTableData($('#org-list').combobox('getValue'));
            }.bind(this)
        });
    };

    this.DisabledEvent = function () {
        $('#edit-btn').prop('disabled', true);
        $('#delete-btn').prop('disabled', true);
        $('#enable-btn').prop('disabled', true);
        $('#disable-btn').prop('disabled', true);
    };
};

$(document).ready(function () {
    var app = new App();
    app.Startup();
});