var records = new Array();

$(function () {
    // 测试方法
    test();


    $('.article-wrapper').css('height', $(window).height() - 65);
    $(".article-col-content").css('height', $(window).height() - 140);
    $(".article-col-content").niceScroll({
        styler:"fb",
        cursorcolor:"#4ECDC4",
        cursorwidth: '5',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled:false,
        cursorborder: ''
    });

    // 时间选择
    $('#start-time, #end-time, #new-time').datetimepicker({
        language: 'zh-CN',
        autoclose: true,
        todayBtn : true,
        keyboardNavigation: false,
        initialDate: new Date(),
        endDate: new Date(),
        minuteStep: 5,
        format: 'yyyy-mm-dd hh:ii:ss'
    });

    // 表单
    $('#article-create-form').validationEngine('attach', {
        promptPosition: 'inline',
        binded: true,
        scroll: true,
        autoHidePrompt: true,
        showOneMessage: true,
        addPromptClass: 'formError-text'
    });
    $('#insert-form').validationEngine('attach', {
        promptPosition: 'centerRight',
        binded: true,
        scroll: true,
        autoHidePrompt: true,
    });

    // 选择机器人
    $('#robot').unbind('change').bind('change', function (event) {
        event.preventDefault();
        var _this = $(this);
        var robot_id = _this.val();
        if (robot_id && robot_id != 0) {
            getGroups(robot_id);
        }else{
            $('#groups').addClass('hidden');
        }
    });

    // 加载记录
    $('#load-records').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var $btn = _this.button('loading');
        var robot_id = $('#robot').val();
        var group_id = $('#group').val();
        var start = $.trim($('#start-time').val());
        var end = $.trim($('#end-time').val());
        if (robot_id && group_id && robot_id != 0 && group_id != 0 && start && end) {
            // 清空右侧内容
            clearRightPanel2And3();
            // 加载数据
            getRecords(robot_id, group_id, start, end, $btn);
        }else if (!start || !end) {
            new PNotify({title: '提示', text: '请选择时间区间', type: "error"});
            $btn.button('reset');
            return;
        }else{
            new PNotify({title: '提示', text: '请选择接受账号和群', type: "error"});
            $btn.button('reset');
            return;
        }
    });

    // 封面
    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,jpeg"} // 限定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);
            },
        }
    });

    // 保存
    $("#btn-save").unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var $btn = _this.button('loading');
        var valid = $('#article-create-form').validationEngine('validate');
        if (valid && records.length > 0) {
            var contentArr = new Array();
            for (var i = 0; i < records.length; i++) {
                var content = new Object();
                var data = new Object();
                var user = new Object();

                user.nickname = records[i].user.nickname;
                user.avatar = records[i].user.avatar;
                data = records[i].data;
        
                if (records[i].is_robot == 1) {
                    content.position = 'right';
                }else{
                    content.position = 'left';
                }
                content.type = parseInt(records[i].type);
                content.id = parseInt(records[i].id);

                content.user = user;
                content.data = data;
                content.received_at = records[i].received_at;

                contentArr.push(content);
            }
            $('#content').val(JSON.stringify(contentArr));
            // $('#article-create-form')[0].submit();
            saveArticle($btn);
        }else if (valid) {
            new PNotify({title: '提示', text: '精华内容不能为空'});
            $btn.button('reset');
            return;
        }else{
            new PNotify({title: '提示', text: '请将数据填写完整', type: "error"});
            $btn.button('reset');
            return;
        }
    });
});

/**
 * 获取机器人的群
 * @param  {[type]} robot_id [description]
 * @return {[type]}          [description]
 */
function getGroups (robot_id) {
    $.ajax({
        url: '/admin/Group/groups',
        type: 'POST',
        dataType: 'json',
        data: {
            robot_id: robot_id
        },
        cache: false
    })
    .done(function(res) {
        var res = JSON.parse(res);
        if (res.error) {
            new PNotify({title: '提示',text: res.msg, 'type': 'error'});
        }else{
            $('#groups-wrapper').removeClass('hidden');
            var html = template('groups-tmp', res.data);
            document.getElementById('group').innerHTML = html;
        }
    })
    .fail(function() {
        new PNotify({title: '提示', text: '网络请求失败', 'type': 'error'});
    })
    .always(function() {
    });
}

/**
 * 获取消息记录
 * @param  {[type]} robot_id [description]
 * @param  {[type]} group_id [description]
 * @param  {[type]} start    [description]
 * @param  {[type]} end      [description]
 * @param  {[type]} btn      [description]
 * @return {[type]}          [description]
 */
function getRecords (robot_id, group_id, start, end, btn) {
    $.ajax({
        url: '/admin/Article/records',
        type: 'POST',
        dataType: 'json',
        data: {
            rid: robot_id,
            gid: group_id,
            start: start,
            end: end,
        },
        cache: false
    })
    .done(function(res) {
        var res = JSON.parse(res);
        if (res.error) {
            new PNotify({title: '提示', text: res.msg, 'type': 'error'});
        }else{
            if (res.data.length == 0) {
                new PNotify({title: '提示', text: '共获取到 0 条数据'});
                return;
            }
            records = res.data;

            var html = "";
            for (var i = 0; i < res.data.length; i++) {
                if (res.data[i].is_robot == 1) {
                    html += template('right-record-item', res.data[i]);
                }else{
                    html += template('left-record-item', res.data[i]);
                }
            }
            $('#records-container').prepend(html);

            // 初始化第三方库
            initThirdPlugins();
            // 元素点击事件
            bindClickEventToMsgItem();
        }
    })
    .fail(function() {
        new PNotify({title: '提示', text: '网络请求失败', 'type': 'error'});
    })
    .always(function() {
        if (btn) {
            btn.button('reset');
        };
    });
}

/**
 * 保存精华
 * @param  {[type]} btn [description]
 * @return {[type]}     [description]
 */
function saveArticle (btn) {
    $.ajax({
        url: '/admin/article/create',
        type: 'POST',
        dataType: 'json',
        data: $("#article-create-form").serialize(),
        cache: false
    })
    .done(function(res) {
        var res = JSON.parse(res);
        if (res.error) {
            new PNotify({title: '提示', text: res.msg, 'type': 'error'});
        }else{
            new PNotify({title: '提示', text: res.msg, 'type': 'success'});
            setTimeout(function () {
                window.location.href = '/admin/article';
            }, 1500);
        }
    })
    .fail(function() {
        new PNotify({title: '提示', text: '网络请求失败', 'type': 'error'});
    })
    .always(function() {
        if (btn) {
            btn.button('reset');
        };
    });
}

/**
 * 元素点击事件绑定
 * @return {[type]} [description]
 */
function bindClickEventToMsgItem () {
    $('.msg-item').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        _this.addClass("active").siblings(".msg-item").removeClass("active");
        var oid = _this.attr('oid');

        var record = _.find(records, function (item) {
            return item.id == oid;
        });
        if (record) {
            switch (record.type) {
                case 1: case 7:
                    setTextTmp(record, oid);
                    break;
                case 2:
                    setImageTmp(record, oid);
                    break;
                case 3:
                    setGraphicTmp(record, oid);
                    break;
                case 4:
                    setFileTmp(record, oid);
                    break;
                default:
                    new PNotify({title: '提示', text: '不支持该类型消息'});
                    break;
            }
        }else{
            new PNotify({title: '提示', text: '发生了错误，请刷新', 'type': 'error'});
        }
    });
}

/**
 * 设置文本模板
 * @param {[type]} data [description]
 * @param {[type]} oid  [description]
 */
function setTextTmp (data, oid) {
    var $container = $('#action-container');
    var html = template('text-tmp', data);
    $container.html(html);

    bindRightActions($container);
}

/**
 * 设置图片模板
 * @param {[type]} data [description]
 * @param {[type]} oid  [description]
 */
function setImageTmp (data, oid) {
    var $container = $('#action-container');
    var html = template('image-tmp', data);
    $container.html(html);

    bindRightActions($container);
}

/**
 * 设置图文模板
 * @param {[type]} data [description]
 * @param {[type]} oid  [description]
 */
function setGraphicTmp (data, oid) {
    var $container = $('#action-container');
    var html = template('graphic-tmp', data);
    $container.html(html);

    bindRightActions($container);
}

/**
 * 设置文件模板
 * @param {[type]} data [description]
 * @param {[type]} oid  [description]
 */
function setFileTmp (data, oid) {
    var $container = $('#action-container');
    var html = template('file-tmp', data);
    $container.html(html);
    
    bindAudioAction();
    bindRightActions($container);
}

/**
 * 绑定语音播放时间
 * @return {[type]} [description]
 */
function bindAudioAction () {
    $('.app-voice').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var _state = _this.children('.app-voice-state');
        var src = _this.attr('voiceSrc');
        var audio = document.getElementById('audio_ele');
        if (audio !== null) {
            $('#audio_ele').find('source').attr('src', src);
            if (audio.pause) {
                audio.pause;
            };
            audio.load();
            audio.play();
            _state.removeClass('app-voice-pause').addClass('app-voice-play');
            audio.addEventListener('ended', function () {
                _state.removeClass('app-voice-play').addClass('app-voice-pause');
            });
        }else{
            new PNotify({title: '提示', text: '不支持播放'});
        }
    });
}

/**
 * 初始化第三方插件
 * @return {[type]} [description]
 */
function initThirdPlugins () {
    // fancybox初始化
    $("[data-fancybox]").fancybox({
        image : {
            protect: true
        }
    });
    // sortable初始化
    var records_container = document.getElementById("records-container");
    Sortable.create(records_container, {
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        dragClass: "sortable-drag",
        dataIdAttr: 'oid',
        onEnd: function (evt) {
            moveItem($(evt.item).attr('oid'), evt.oldIndex, evt.newIndex);
        },
    });
}

/**
 * 绑定右侧区域事件
 * @return {[type]} [description]
 */
function bindRightActions ($container) {
    // 使得input默认显示文本末尾
    var $avatar = $container.find('input[name=avatar]');
    $avatar.scrollLeft($avatar.offset().left);

    // 删除
    $container.find('.btn-delete').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var oid = _this.attr('oid');

        deleteItem(oid);
    });

    // 更新
    $container.find('.btn-update').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var oid = _this.attr('oid');
        var type = _this.attr('otype');

        var nickname = $container.find('input[name=nickname]').val();
        var avatar = $container.find('input[name=avatar]').val();
        var received_at = $container.find('input[name=received_at]').val();
        var content = $container.find('textarea[name=content]').val();
        var uri = $container.find('input[name=uri]').val();
        var title = $container.find('input[name=title]').val();
        var desc = $container.find('textarea[name=desc]').val();

        var data = new Object();
        data.nickname = nickname;
        data.avatar = avatar;
        data.received_at = received_at;

        if (type == 1 || type == 7) {
            data.content = content;
        }else if (type == 2 || type == 4) {
            data.uri = uri;
        }else if (type == 3) {
            data.title = title;
            data.desc = desc;
        }

        updateItem(oid, data);
    });

    // 插入
    $('.btn-insert').unbind('click').bind('click', function(event){
        event.preventDefault();
        var _this = $(this);
        var oid = _this.attr('oid');
        showInsertDialog(function () {
            var valid = $('#insert-form').validationEngine('validate');
            if (valid) {
                hideInsertDialog();
                var arr = $('#insert-form').serializeArray();
                $('#insert-form')[0].reset();
                var data = new Object();
                for (var i = 0; i < arr.length; i++) {
                    data[arr[i]['name']] = arr[i]['value'];
                };
                insertItem(data, oid);
            }else{
                new PNotify({title: '提示', text: '请将数据填写完整', type: "error"});
            }
        });
    });
}

/**
 * 删除
 * @param  {[type]} oid [description]
 * @return {[type]}     [description]
 */
function deleteItem (oid) {
    var record = _.find(records, function (item) {
        return item.id == oid;
    });
    if (record) {
        var idx = _.indexOf(records, record);
        records.splice(idx, 1);
        $('#msg-item-'+oid).remove();
        $('#action-container').html('');
    };
}

/**
 * 更新
 * @param  {[type]} oid  [description]
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
function updateItem (oid, data) {
    var record = _.find(records, function (item) {
        return item.id == oid;
    });
    if (record) {
        record.user.nickname = data.nickname;
        record.user.avatar = data.avatar;
        record.received_at = data.received_at;
        if (record.type == 1 || record.type == 7) {
            record.data.content = data.content;
        }else if (record.type == 2 || record.type == 4) {
            record.data.uri = data.uri;
            record.data.filename = getFilename(data.uri);
        }else if (record.type == 3) {
            record.data.title = data.title;
            record.data.desc = data.desc;
        }

        var html = "";
        if (record.is_robot == 1) {
            html = template('right-record-item', record);
        }else{
            html = template('left-record-item', record);
        }
        $('#msg-item-'+oid).replaceWith(html);
        $('#msg-item-'+oid).addClass('active');
        bindClickEventToMsgItem();
    }
}

/**
 * 插入
 * @param  {[type]} data [description]
 * @param  {[type]} oid  [description]
 * @return {[type]}      [description]
 */
function insertItem (data, oid) {
    var record = _.find(records, function (item) {
        return item.id == oid;
    });
    if (record) {
        var idx = _.indexOf(records, record);
        var newRecord = new Object();
        var newUser = new Object();
        var newData = new Object();

        newUser.nickname = data.nickname;
        newUser.avatar = data.avatar;

        if (data.type == 1) {
            newData.content = data.content;
        }else if (data.type == 2 || data.type == 3 || data.type == 4) {
            newData.uri = data.content;
            newData.filename = getFilename(data.content);
        }
        if (data.role == 'right') {
            newRecord.is_robot = 1;
        }else{
            newRecord.is_robot = 0;
        }
        newRecord.type = parseInt(data.type);
        newRecord.id = getRandomId();

        newRecord.user = newUser;
        newRecord.data = newData;
        newRecord.received_at = data.received_at;

        // 更新视图
        var html = "";
        if (newRecord.is_robot == 1) {
            html = template('right-record-item', newRecord);
        }else{
            html = template('left-record-item', newRecord);
        }
        // 插入到数据集合中
        if (data.position == 'top') {
            records.splice(idx, 0, newRecord);
            $('#msg-item-'+oid).before(html);
        }else{
            records.splice(idx+1, 0, newRecord);
            $('#msg-item-'+oid).after(html);
        }
        bindClickEventToMsgItem();
    };
}

/**
 * 移动
 * @param  {[type]} oid      [description]
 * @param  {[type]} oldIndex [description]
 * @param  {[type]} newIndex [description]
 * @return {[type]}          [description]
 */
function moveItem (oid, oldIndex, newIndex) {
    var record = _.find(records, function (item) {
        return item.id == oid;
    });
    if (record) {
        records.splice(oldIndex, 1);
        records.splice(newIndex, 0, record);
    }
}

/**
 * 清空后侧内容区
 * @return {[type]} [description]
 */
function clearRightPanel2And3 () {
    $('#records-container').html('');
    $('#action-container').html('');
}

/**
 * 获取文件名
 * @param  {[type]} path [description]
 * @return {[type]}      [description]
 */
function getFilename (path) {
    var pure_name = path.replace(/(.*\/)*([^.]+).*/ig,"$2");
    var ext = path.substring(path.lastIndexOf('.') + 1);
    return pure_name + "." + ext;
}

/**
 * 生成随机id，防止id重复，从最后一条开始
 * @return {[type]} [description]
 */
function getRandomId () {
    var last = _.max(records, function (record) {
        return parseInt(record.id);
    });
    return parseInt(Math.random()*100, 10) + parseInt(last.id);
}

/**
 * 测试
 * @return {[type]} [description]
 */
function test () {
    var robot_id = 1;
    var group_id = 50;
    var start = "2017-03-07 08:00:00";
    var end = "2017-05-17 23:00:00";

    getRecords(robot_id, group_id, start, end);
}
