/**
 * 添加日志
 */
var showModal = function(msg, time, url) {
    var msg = msg || '出错了';
    var time = time || 3000;
    $(".modal-body").html(msg);
    $(".modal").modal();
    clearTimeout(modalTimer);
    var modalTimer = setTimeout(function() {
        $(".modal").modal('hide');
    }, time);
    if (url !== undefined) {
        $('.modal').on('hidden.bs.modal', function (e) {
            window.location.href = url;
        })
    }
};

var getFormValue = function (name) {
    var formFields = $("#main-form").serializeArray();
    var value = undefined;
    if (name == undefined) {
        return formFields;
    }
    $.each(formFields, function (index, field) {
        if (name == field.name) {
            value = field.value;
            return false;
        }
    });
    return value;
}


var validateForm = function () {
    var title = getFormValue('Blog[title]');
    if (title == undefined || title == '')
        return {error:'请输入标题'};
    var workload = getFormValue('Blog[workload]');
    if (workload == undefined || workload == '')
        return {error:'请输入工作量'};
    else if (!/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(workload))
        return {error:'工作量必须是数字'};

    return true;
};

//检查所选日期是否超过今天
var checkDate = function(chooseDate) {
    var today = new Date();
    var chooseDate = new Date(chooseDate.replace(/-/g, "/"));
    return chooseDate < today;
};

//同步附件
var syncAttach = function() {
    var attach = [];
    $(".file-tr").each(function(i) {
        attach.push($(this).data('attachId'));
    });
    $("input[name='Blog[attach_ids]']").val(attach.join());
}

jQuery(function($) {
    //编辑器
    $('#editor').wysiwyg();

    //提交日志
    $("#submit-btn").on('click', function() {
        //保存编辑器内容
        $("textarea[name='Blog[content]']").val($("#editor").html());

        if ((validate = validateForm()) !== true) {
            showModal(validate.error);
            return false;
        }

        if ($(this).html() == '提  交') 
            $(this).html('提交中...');
        else 
            return false;
        var actionUrl = $("#main-form").attr('action');
        $.post(actionUrl, $("#main-form").serialize(), function(json) {
            if (json.status == 0) {
                showModal(json.info);
                $("#submit-btn").html('提  交');
            }
            else {
                showModal(json.info, 3000, json.url);
            }
        });
    });

    //加载日历
    loadCalendar(workTime);
    $("#calendar-list li a").each(function(index){
        if ($(this).data('date') == workTime) {
            $(this).parent('li').addClass('clickfocus');
            return false;
        }
    });

    //点击日期事件
    $("#calendar-list").on('click', 'a', function() {
        var date = $(this).data('date');
        if (!checkDate(date)) {
            showModal('所选日期不能超过今天');
            return '';
        }
        var linkId = getFormValue('Blog[link_id]')
        var linkType = getFormValue('Blog[link_type]')
        if ($(this).parent('li').hasClass('clickfocus')) {
            return ;
        }
        var obj = $(this);
        //切换日期
        var switchBlog = function() {
            obj.parent('li').siblings().removeClass('clickfocus');
            obj.parent('li').addClass('clickfocus');
            $("input[name='Blog[work_time]']").val(date);
        };

        //检测当前所选日期是否写过日志
        $.getJSON(blogCheckUrl, {work_time:date, link_id:linkId, link_type:linkType}, function(json) {
            if (json.haveWrite == 1) {
                if (confirm(date + '已写过日志了，是否放弃当前内容切换到已写日志？')) {
                    $("input[name='Blog[blog_id]']").val(json.blog.blog_id);
                    $("input[name='Blog[title]']").val(json.blog.title);
                    $("input[name='Blog[workload]']").val(json.blog.workload);
                    $("textarea[name='Blog[content]']").val(json.blog.content);
                    $("input[name='Blog[attach_ids]']").val(json.blog.attach_ids);
                    $("#editor").html(json.blog.content);
                    $(".file-tr").remove();
                    $(".upload-tr").before(json.blog.attach_html);
                    switchBlog();
                }
            }
            else {
                if ($("input[name='Blog[blog_id]']").val() != 0) {
                    if (confirm('是否放弃当前编辑内容?')) {
                        $("input[name='Blog[blog_id]']").val(0);
                        $("textarea[name='Blog[content]']").val('');
                        $("input[name='Blog[title]']").val('');
                        $("input[name='Blog[workload]']").val(8);
                        $("input[name='Blog[attach_ids]']").val('');
                        $(".file-tr").remove();
                        $("#editor").html('');
                        switchBlog();
                    }
                }
                else {
                    switchBlog();
                }
            }
        });

    });

    //附件上传
    $('#fileupload').fileupload({
        dataType: 'json',
        done: function (e, data) {
            var downUrl = $("#fileupload").data('downUrl');
            downUrl = downUrl + (downUrl.indexOf('?') == -1 ? '?' : '&') + 'id=';
            if (data.result.status == 1) {
                var fileTpl = ' <tr class="file-tr" data-attach-id="' + data.result.aid + '"> <td></td> <td class="icon-download-alt"><a href="' + downUrl + data.result.aid + '">' + data.result.name + '</a><button type="button" class="btn btn-filedelete delete-file  icon-trash"></button></td> </tr>';
                $(".upload-tr").before(fileTpl);
                syncAttach();
            }
        }
    });

    //删除附件
    $(document).on('click', '.delete-file', function() {
        $(this).parent().parent('tr').remove();
        syncAttach();
    });

});
