var HistoryPanel = function (parent) {
    this.Parent = parent;
    this.ResultList = new ResultList(this, '#history-result-list');

    this.Startup = function () {
        this.ResultList.Startup();
        this.InitDataGrid();
        this.InitDateTimes();

        $('#dialog-close').on('click', this.HideEditDialog.bind(this));
        $('#delete-dialog-close').on('click', this.HideDeleteDialog.bind(this));
        $('#dialog-cancel').on('click', this.HideDeleteDialog.bind(this));
        $('#query-button').on('click', this.OnQueryButtonClick.bind(this));
        $('#query-button').trigger('click');
    };

    this.InitDataGrid = function () {
        $('#task-grid').datagrid({
            columns: [[
                { field: 'ReleaseTime', title: '释放时间', align: 'center', width: 80, formatter: this.ShowDetailInfo.bind(this) },
                { field: 'Height', title: '高度(米)', align: 'center', width: 30 },
                { field: 'Manage', title: '操作', align: 'center', width: 40, formatter: this.OperateColumn.bind(this) }
            ]],
            striped: true,
            singleSelect: false,
            fitColumns: true,
            fit: true,
            scrollbarSize: 0,
            onLoadSuccess: function (data) {
                for (var i = 0; i < data.rows.length; i++) {
                    $('.datagrid-btable tr').eq(i).find('.edit').on('click', this.ShowEditDialog.bind(this, i));
                    $('.datagrid-btable tr').eq(i).find('.delete').on('click', this.ShowDeleteDialog.bind(this, i));
                }
            }.bind(this),
            onSelect: this.OnTaskSelected.bind(this),
            onUnselect: this.OnTaskUnselected.bind(this)
        });
    };

    this.InitDateTimes = function () {
        $('#start-date').datetimebox({
            panelWidth: 190,
            panelHeight: 230,
            panelAlign: 'right',
            showSeconds: false,
            currentText: '现在'
        });

        $('#end-date').datetimebox({
            panelWidth: 190,
            panelHeight: 230,
            panelAlign: 'right',
            showSeconds: false,
            currentText: '现在'
        });

        var startDate = moment(new Date()).subtract(1, 'months').format('YYYY/MM/DD HH:mm');
        $('#start-date').datetimebox("setValue", startDate);
    };

    this.OnTaskSelected = function (index, row) {
        this.LoadData(row);

        var selections = $('#task-grid').datagrid('getSelections');
        if (selections.length > 1) {
            this.ResultList.DisableSwitch = true;
            this.ResultList.ShowMask();
        }
    };

    this.OnTaskUnselected = function (index, row) {
        // Remove data layer
        this.Parent.Map.RemoveLayer(row.Id);

        // Reset result list if no task selected
        var selections = $('#task-grid').datagrid('getSelections');
        if (selections.length === 0) {
            this.ResultList.Reset();
            return;
        }

        // Resize mask of result list
        this.ResultList.DisableSwitch = (selections.length !== 1);
        this.ResultList.ResizeMask();
    };

    this.LoadData = function (task) {
        $.getJSON("http://{0}/mg/getresult/{1}.json".format(Config.ApiRoot, task.Id), function (data) {
            this.Parent.Map.LoadAverageData(task.Id, task, data);
            this.ResultList.SetData(task.Id, [task.Latitude, task.Longitude], data);
        }.bind(this));
    };

    this.OnQueryButtonClick = function () {
        this.ReloadAllLabel();
        this.ReloadDataGrid();
    };

    this.ReloadAllLabel = function () {
        $.ajax({
            type: "POST",
            dataType: 'text',
            url: '/Menggu/GetUserTags',
            data: {
                userId: parseInt($('#user-info').attr('userid'))
            },
            success: function (result) {
                this.CreateAllLabels(JSON.parse(result));
                this.Relayout();
            }.bind(this)
        });
    };

    this.CreateAllLabels = function (data) {
        var list = $('.all-label-list');
        if (data.length === 0) {
            list.find('.no-tags').show();
            return;
        }

        data.forEach(function (item) {
            var label = $('<a href="javascript:;" tagId="{0}">{1}<span class="clear-btn"><i></i></span></a>'.format(item.Id, item.Name));
            label.on('click', this.SetActiveLabel.bind(this));
            label.find('.clear-btn').on('click', this.RemoveAllLabel.bind(this));
            list.append(label);
        }.bind(this));
    };

    this.SetActiveLabel = function (event) {
        $(event.target).toggleClass('active');
        this.ReloadDataGrid();
    };

    this.RemoveAllLabel = function (event) {
        var aLabel = null;

        if ($(event.target).parent().is('a'))
            aLabel = $(event.target).parent();
        else
            aLabel = $(event.target).parents('a');

        aLabel.remove();

        if ($('.all-label-list a').length === 0)
            $('.all-label-list').find('.no-tags').show();

        this.Relayout();
        this.ClearLabel(parseInt(aLabel.text()));
    };

    this.ClearLabel = function (name) {
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/Menggu/DeleteTagsByName',
            data: {
                userId: parseInt($('#user-info').attr('userid')),
                name: name
            },
            success: function (result) {
            }.bind(this)
        });
    };

    this.GetSeletedLabelId = function () {
        var tagIds = [];
        var items = $('.all-label-list a.active');
        items.each(function (index, item) {
            var text = $(item).text();
            tagIds.push(parseInt(text));
        }.bind(this));

        return tagIds;
    };

    this.ReloadDataGrid = function () {
        $('#task-grid').datagrid({
            method: "POST",
            url: '/Menggu/GetTasks',
            queryParams: {
                userId: parseInt($('#user-info').attr('userid')),
                startTime: $("#start-date").datetimebox('getValue'),
                endTime: $("#end-date").datetimebox('getValue'),
                tags: this.GetSeletedLabelId()
            }
        });
    };

    this.ShowDetailInfo = function (val) {
        return moment(val).format('YYYY/MM/DD HH:mm');
    };

    this.OperateColumn = function () {
        return '<span class="edit"></span><span class="delete"></span>';
    };

    this.ShowEditDialog = function (i, event) {
        event.stopPropagation();
        $('#label').val('');
        $('.dialog-manage').show();
        $('#dialog-label-list').find('a').remove();
        $('#dialog-label-list').find('h2').remove();

        var rows = $("#task-grid").datagrid('getRows');
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/Menggu/GetTaskTags',
            data: {
                userId: parseInt($('#user-info').attr('userid')),
                taskId: rows[i].Id
            },
            success: function (result) {
                console.log(result);
                this.CreateDialogLabel(result);
                this.SetDialogHeight();
                $('#dialog-add-label').off('click').on('click', this.DialogAddLabelButton.bind(this, rows[i].Id));
            }.bind(this)
        });
    };

    this.CreateDialogLabel = function (data) {
        var list = $('#dialog-label-list');
        list.find('a').remove();

        if (data.length === 0) {
            list.find('.dialog-no-tags').show();
            return;
        }
        data.forEach(function (item) {
            var label = $('<a href="javascript:;" tagId="{0}">{1}<span class="clear-btn"><i></i></span></a>'.format(item.Id, item.Name));
            label.find('.clear-btn').on('click', this.RemoveLabel.bind(this));
            list.append(label);
        }.bind(this));
    };

    this.ShowDeleteDialog = function (i, event) {
        event.stopPropagation();
        $('.dialog-delete').show();

        var row = $("#task-grid").datagrid('getRows')[i];
        $('.dialog-clear h2').text('确定删除释放时间为「{0}」的任务吗?'.format(moment(row.ReleaseTime).format('YYYY/MM/DD HH:mm')));
        $('#dialog-sure').on('click', this.DeleteCurrentLabel.bind(this, row.Id));
    };

    this.DeleteCurrentLabel = function (id) {
        this.HideDeleteDialog();

        $.ajax({
            type: "POST",
            url: '/Beijing/DeleteTask',
            async: true,
            data: {
                id: id
            },
            success: function () {
                this.ReloadDataGrid();
            }.bind(this)
        });
    };

    this.HideDialog = function () {
        this.Parent.HideDialog();
    };

    this.HideEditDialog = function () {
        $('.dialog-manage').hide();
    };

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

    this.DialogAddLabelButton = function (id) {
        var value = $('#label').val().trim();
        if (value.length === 0)
            return;

        $.ajax({
            type: "POST",
            dataType: 'json',
            data: {
                userId: parseInt($('#user-info').attr('userid')),
                taskId: id,
                name: value
            },
            url: '/Menggu/AddTag',
            success: function (result) {
                var label = '<a href="javascript:;" tagid="{0}">{1}<span class="clear-btn"><i></i></span></a>'.format(result, value);
                $('#dialog-label-list').append(label).find('.clear-btn').on('click', this.RemoveLabel.bind(this));
                this.SetDialogHeight();
            }.bind(this)
        });


    };

    this.RemoveLabel = function (event) {
        var label = null;
        if ($(event.target).parent().is('a'))
            label = $(event.target).parent();
        else
            label = $(event.target).parents('a');

        label.remove();
        this.DeleteLabel(parseInt(label.attr('tagid')));
        this.SetDialogHeight();
    };

    this.DeleteLabel = function (id) {
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/Menggu/DeleteTag',
            data: {
                id: id
            },
            success: function (result) {
            }.bind(this)
        });
    };

    this.SetDialogHeight = function () {
        var dialog = $('.dialog-manage .dialog-content');
        var label = $('#dialog-label-list');
        var number = label.find('a').length;
        if (number > 3) {
            label.find('h2').hide();
            dialog.height(Math.ceil(number / 3) * 40 + 100);
        }
        else if (number === 0) {
            label.find('h2').show();
            dialog.height(140);
        }
        else {
            label.find('h2').hide();
            dialog.height(138);
        }
    };

    this.Relayout = function () {
        var windowHeight = $(window).height();
        var labelHeight = $('#history-slider').find('.label-list:first').height();
        var tableHeight = $('#history-slider').find('.calc-table:first').height();

        var resultList = $('#history-result-list');
        resultList.find('.calc-list ul').height(windowHeight - labelHeight - tableHeight - 500);
        this.ResultList.ResizeMask();
    };
};