$(function () {
    $('[data-toggle="tooltip"]').tooltip();

    // 右侧详情
    $('.btn-detail').unbind('click').bind('click', function (event) {
        event.stopPropagation();
        event.preventDefault();
        document.getElementById('right-detail-content').innerHTML = "";
        var url = "/admin/Article/read";
        var oid = $(this).attr('oid');
        showRightDetail(function () {
            $.get(url + "/id/" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    var html = template('article', res.data);
                    document.getElementById('right-detail-content').innerHTML = html;
                }
            });
        });
    });

    // 更新
    $('.btn-edit').unbind('click').bind('click', function (event) {
        event.preventDefault();
        document.getElementById('right-detail-content').innerHTML = "";
        var url = "/admin/Article/update";
        var oid = $(this).attr('oid');
        showRightDetail(function () {
            $.get(url + "/id/" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    var html = template('article-update', res.data);
                    document.getElementById('right-detail-content').innerHTML = html;

                    initPosterUpload();
                    $('#btn-update').unbind('click').bind('click', function (event) {
                        event.preventDefault();
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        update(oid, $btn);
                    });
                }
            });
        });
    });

    // 推送
    $('.btn-push').unbind('click').bind('click', function (event) {
        event.preventDefault();
        document.getElementById('right-detail-content').innerHTML = "";
        var url = "/admin/Article/readSpaces";
        var oid = $(this).attr('oid');
        showRightDetail(function () {
            $.get(url + "/id/" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    var html = template('spaces-tmp', res.data);
                    document.getElementById('right-detail-content').innerHTML = html;
                    // 管理并推送
                    $('#btn-publish').unbind('click').bind('click', function (event) {
                        event.preventDefault();
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        var sid = $('#space').val();
                        var auto_publish = $('input[name=auto_publish]:checked').val();
                        if (sid && sid != 0) {
                            publish(oid, sid, auto_publish, $btn);
                        } else {
                            new PNotify({
                                title: '提示',
                                text: '请选择群空间'
                            });
                            $btn.button('reset');
                            return;
                        }
                    });
                    // 手动推送
                    $('.btn-hand-publish').unbind('click').bind('click', function (event) {
                        event.preventDefault();
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        var oid = _this.attr('oid');
                        if (oid && oid != 0) {
                            publishToGroup(oid, $btn);
                        } else {
                            new PNotify({
                                title: '提示',
                                text: '参数错误，请刷新'
                            });
                            $btn.button('reset');
                            return;
                        }
                    });
                    // 删除关联
                    $('.btn-hand-delete').unbind('click').bind('click', function (event) {
                        event.preventDefault();
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        var oid = _this.attr('oid');
                        if (oid && oid != 0) {
                            showDialog("删除", "确定删除群精选与群的关联？", function () {
                                deleteSpaceRelation(oid, $btn);
                            }, function () {
                                $btn.button('reset');
                            });
                        } else {
                            new PNotify({
                                title: '提示',
                                text: '参数错误，请刷新'
                            });
                            $btn.button('reset');
                            return;
                        }
                    });
                }
            });
        });
    });

    // 删除群精选
    $('.btn-delete').unbind('click').bind('click', function (event) {
        var url = "/admin/Article/delete";
        var oid = $(this).attr('oid');
        showDialog("删除群精选", "确定删除群精选？", function () {
            $.get(url + "/id/" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    window.location.reload();
                }
            });
        });
    });

    /**
     * 更新
     * @param  {[type]} oid [description]
     * @param  {[type]} btn [description]
     * @return {[type]}     [description]
     */
    function update(oid, btn) {
        $.ajax({
                url: '/admin/Article/update/id/' + oid,
                type: 'POST',
                dataType: 'json',
                data: $('#article-update-form').serialize(),
                cache: false
            })
            .done(function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    window.location.reload();
                }
            })
            .fail(function () {
                new PNotify({
                    title: '提示',
                    text: '网络请求失败',
                    'type': 'error'
                });
            })
            .always(function () {
                if (btn) {
                    btn.button('reset');
                };
            });
    }

    /**
     * 发布群精华到群空间
     * @param  {[type]} oid [description]
     * @param  {[type]} sid [description]
     * @param  {[type]} btn [description]
     * @return {[type]}     [description]
     */
    function publish(oid, sid, auto, btn) {
        $.ajax({
                url: '/admin/Article/publish',
                type: 'POST',
                dataType: 'json',
                data: {
                    id: oid,
                    sid: sid,
                    auto_publish: auto
                },
                cache: false
            })
            .done(function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    window.location.reload();
                }
            })
            .fail(function () {
                new PNotify({
                    title: '提示',
                    text: '网络请求失败',
                    'type': 'error'
                });
            })
            .always(function () {
                if (btn) {
                    btn.button('reset');
                };
            });
    }

    /**
     * 发布到微信群
     * @param  {[type]} oid [description]
     * @param  {[type]} sid [description]
     * @param  {[type]} btn [description]
     * @return {[type]}     [description]
     */
    function publishToGroup(oid, btn) {
        $.ajax({
                url: '/admin/Article/publishToGroup',
                type: 'POST',
                dataType: 'json',
                data: {
                    id: oid
                },
                cache: false
            })
            .done(function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    window.location.reload();
                }
            })
            .fail(function () {
                new PNotify({
                    title: '提示',
                    text: '网络请求失败',
                    'type': 'error'
                });
            })
            .always(function () {
                if (btn) {
                    btn.button('reset');
                };
            });
    }

    /**
     * 删除空间精华关联
     * @param  {[type]} oid [description]
     * @param  {[type]} btn [description]
     * @return {[type]}     [description]
     */
    function deleteSpaceRelation(oid, btn) {
        $.ajax({
                url: '/admin/Article/deleteSpaceRelation',
                type: 'POST',
                dataType: 'json',
                data: {
                    id: oid
                },
                cache: false
            })
            .done(function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                } else {
                    window.location.reload();
                }
            })
            .fail(function () {
                new PNotify({
                    title: '提示',
                    text: '网络请求失败',
                    'type': 'error'
                });
            })
            .always(function () {
                if (btn) {
                    btn.button('reset');
                };
            });
    }

    /**
     * 初始化图片上传控件
     * @return {[type]} [description]
     */
    function initPosterUpload() {
        var imgUploader = Qiniu.uploader({
            runtimes: 'html5,flash,html4', // 上传模式，依次退化
            browse_button: 'poster', // 上传选择的点选按钮，必需
            uptoken_url: '/admin/upload/uptoken', // Ajax请求uptoken的Url
            get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的uptoken
            domain: 'http://botfile.imgondar.com/', // bucket域名，下载资源时用到，必需
            container: 'image-input-container', // 上传区域DOM ID，默认是browser_button的父元素
            max_file_size: '100mb', // 最大文件体积限制
            flash_swf_url: '/static/plupload/Moxie.swf', //引入flash，相对路径
            max_retries: 3, // 上传失败最大重试次数
            dragdrop: true, // 开启可拖曳上传
            drop_element: 'chating-text', // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: '4mb', // 分块上传时，每块的体积
            auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
            multi_selection: false,
            unique_names: true,
            filters: {
                mime_types: [{
                        title: "Image files",
                        extensions: "jpg,gif,png"
                    } // 限定jpg,gif,png后缀上传
                ]
            },
            init: {
                'FilesAdded': function (up, files) {},
                'BeforeUpload': function (up, file) {},
                'UploadProgress': function (up, file) {},
                'UploadComplete': function () {},
                'FileUploaded': function (up, file, info) {
                    var domain = up.getOption('domain');
                    var res = $.parseJSON(info);
                    // 获取上传成功后的文件的Url
                    var sourceLink = domain + res.key;
                    $('#poster').val(sourceLink);

                    imgUploader.stop();
                    imgUploader.removeFile(file);
                },
                'Error': function (up, err, errTip) {
                    //上传出错时，处理相关的事情
                    new PNotify({
                        title: '提示',
                        text: "文件上传出错"
                    });
                    imgUploader.stop();
                    imgUploader.removeFile(err.file);
                },
            }
        });
    }
});