/**
 * 时间轴模板功能类
 * Created by ythuang on 14-7-8.
 */

function HistoryItem() {
    this.time;
    this.img;
    this.title;
    this.text;
};

function HistoryTemplate() {
    var _self = this;
    var _timeNum = 3;
    this.HistoryItems = [];
    var _currentTimeIndex = 0; // 当前编辑时间轴
    this.TimeNameArr = [];
    var _uEditorDlg = false;

    /**
     * 初始化，绑定页面事件
     */
    this.init = function () {

        $("#list_time").unbind('change');
        $("#list_time").change(function () {
            var timeNum = parseInt($("#list_time option:selected").text());
            _self.TimeNameArr = [];
            $(".time_item").each(function (i) {
                if (_self.HistoryItems.length > i) {
                    _self.HistoryItems[i].time = $(this).val();
                }

                _self.TimeNameArr.push($(this).val());
            });
            _timeNum = timeNum;
            _self.chooseTimesNum(timeNum);
        });

        $(".history_title").unbind('focusout');
        $(".history_title").focusout(function () {
            var title = $(this).val();
            if (title != "请输入标题" && title != "") {
                $(".history_title").val(title);
            } else {
                $(".history_title").val("");
            }
        })

        // 时间轴标题限制
        $(".history_title").unbind('input propertychange');
        $(".history_title").bind('input propertychange', function () {
            var titleLengthArr = calcStrLength(this.value, 70);
            var titleStrLength = titleLengthArr[0];
            var mostIndex = titleLengthArr[1];
            if (titleStrLength > 70) {
                //标题过长，截断处理
                $(this).val($(this).val().substr(0, mostIndex + 1));
            }
        });

        // 时间点名称限制
        $(".time_item").unbind('input propertychange');
        $(".time_item").bind('input propertychange', function () {
            if (this.value.length > 10) {
                $(this).val($(this).val().substr(0, 10));
            }
        });

        // 时间点标题限制
        $("#itemTitle").unbind('input propertychange');
        $("#itemTitle").bind('input propertychange', function () {
            if (this.value.length > 23) {
                $(this).val($(this).val().substr(0, 23));
            }
        });

        // 编辑时间点内容
        $("#itemTitle").unbind('click');
        $('#itemText').click(function () {
            _self.saveCurrentTime(null);

            var _tar = $(this);
            var _prog = _tar[0].getBoundingClientRect();
            var _str = _tar[0].innerHTML || '';
            _tar.html('');

            $(_tar).off();
            var _uedtorDom = $('<div id ="editor_dom" style="font-size: 12px;position:absolute;z-index:1988;word-wrap: break-word;border: 1px solid #c6c6c6;border-radius: 5px;"></div>');
            _uedtorDom.css('width', _prog.width);
            _uedtorDom.css('height', 108);
            _uedtorDom.css('left', _prog.left);
            _uedtorDom.css('top', _prog.top);
            $('body').append(_uedtorDom);
            var editor = UE.getEditor('editor_dom', {
                initialFrameWidth: '100%'
            });

            var _textMask = '<div id="ue_text_mask" class="ue-text-mask"></div>';
            $('body').append(_textMask);
            editor.addListener('ready', function (e) {
                editor.setContent(_str);
                _uEditorDlg = true;
            });
            editor.addListener('destroy', function (e) {
                _uEditorDlg = false;
            });
            $('#ue_text_mask').on('click', function (e) {
                $(this).remove();
                _str = editor.getContent();
                editor.destroy();
                _uedtorDom.remove();
                _tar.html(_str);

                _self.HistoryItems[_currentTimeIndex].text = _str;
                _self.showTime(_currentTimeIndex);
            });
        });

        // 选择图片
        $(".add_time_img").unbind('click');
        $(".add_time_img").click(function () {
            _self.selectHistoryImg();
        });

        // 排序
        $("#time_sort").unbind('dragsort');
        $("#time_sort").dragsort({ dragSelector: "li", dragBetween: true, dragEnd: saveOrder, placeHolderTemplate: "" });
        function saveOrder() {
            $("#time_sort li").css({
                'position': 'relative',
                'opacity': '1',
                'z-index': '1',
                'height': '27px',
                'width': '199px',
                'top': '0',
                'left': '0'
            });
            _self.timeSortComplete(function () {
            });
            timeListClick();
        }
    }

    function timeListClick() {
        var li_height = 50;
        $("#time_sort li").unbind('click');

        $("#time_sort li").each(function (i) {
            $(this).click(function () {
                $("#time_sort li").find("input").each(function (j) {
                    if (i == j && i != 0) {
                        $("#time_sort").animate({"margin-top": -li_height * (j - 1) + "px"}, 200);
                    }
                });
            });
        });
    }


    //计算标题整体字符所占长度
    function calcStrLength(str, charLength) {
        var len = 0;
        //最多实际能放下的“当前”字符串的长度位置
        var mostIndex = 0;
        for (var i = 0; i < str.length; i++) {
            var char = str.charCodeAt(i);
            //单字节加1
            if ((char >= 0x0001 && char <= 0x007e) || (0xff60 <= char && char <= 0xff9f)) {
                len++;
            }
            else {
                len += 1.7;
            }
            if (len <= charLength) {
                mostIndex = i;
            }
        }
        return [len, mostIndex];
    }

    /**
     * 选择时间轴个数
     * @param timeNum 时间节点个数
     */
    this.chooseTimesNum = function (timeNum) {
        var html = '<ul class="timeline_list timeline_list2" id="time_sort">';
        if (_self.HistoryItems.length > 0) {
            for (var i = 0; i < timeNum; i++) {
                if (i < _self.HistoryItems.length && _self.HistoryItems.length > 0) {
                    html += '<li><span class="timeline_circle"><a href="javascript:void(0)"></a>' +
                        '<div class="timeline_input"><input class="time_item" type="text" value="' +
                        _self.HistoryItems[i].time + '" placeholder="输入时间"></div></span>' +
                        '<div style="display: none;">' +
                        '<div class="hcontent">' + _self.HistoryItems[i].text + '</div>' +
                        '<div class="htitle">' + _self.HistoryItems[i].title + '</div>' +
                        '<div class="hurl">' + _self.HistoryItems[i].img + '</div>' +
                        '</div>' +
                        '</li>';
                } else if(i < _self.TimeNameArr.length && _self.TimeNameArr.length > 0) {
                    html += '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="timeline_input"><input class="time_item" type="text" lang="x" value="' + _self.TimeNameArr[i] + '" placeholder="输入时间"></div></span></li>';
                } else {
                    html += '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="timeline_input"><input class="time_item" lang="x" type="text" placeholder="输入时间"></div></span></li>';
                }
            }
        } else {
            for (var i = 0; i < timeNum; i++) {
                if (i < _self.TimeNameArr.length && _self.TimeNameArr.length > 0) {
                    html += '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="timeline_input"><input class="time_item" type="text" lang="x" value="' + _self.TimeNameArr[i] + '" placeholder="输入时间"></div></span></li>';

                } else {
                    html += '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="timeline_input"><input class="time_item" type="text" lang="x" placeholder="输入时间"></div></span></li>';
                }
            }
        }
        html += '</ul>';

        var dom = $(html);
        $("#times_list").html(dom);
        _self.init();
        timeListClick();
    }


    this.getTimeNum = function (callback) {
        if (callback) {
            callback(_timeNum);
        }
    }

    this.timeSortComplete = function (callback) {
        var flag = true;
        var historyItemsTmp = [];
        $(".time_item").each(function (i) {
            var historyItem = new HistoryItem();
            if ($(this).val() === '') {
                flag = false
            }
            historyItem.time = $(this).val();
            historyItem.img = $(this).parents('li').find('.hurl').length === 0 ? '' : $(this).parents('li').find('.hurl')[0].innerHTML;
            historyItem.title = $(this).parents('li').find('.htitle').length === 0 ? '' : $(this).parents('li').find('.htitle')[0].innerHTML;
            historyItem.text = $(this).parents('li').find('.hcontent').length === 0 ? '' : $(this).parents('li').find('.hcontent')[0].innerHTML;
            historyItemsTmp.push(historyItem);
        });
        _self.HistoryItems = historyItemsTmp;
        if (flag) {
            _self.HistoryItems = historyItemsTmp;
        }
        if (callback) {
            callback(flag);
        }
    }

    /**
     * 创建数组
     */
    this.createTime = function (callback) {
        $(".time_item").each(function (i) {
            if (_self.HistoryItems.length > 0) {
                if (i < _self.HistoryItems.length) {
                    _self.HistoryItems[i].time = $(this).val();
                } else {
                    var historyItem = new HistoryItem();
                    historyItem.time = $(this).val();
                    historyItem.img = '';
                    historyItem.title = '';
                    historyItem.text = '';
                    _self.HistoryItems.push(historyItem);
                }
            } else {
                var historyItem = new HistoryItem();
                historyItem.time = $(this).val();
                historyItem.img = '';
                historyItem.title = '';
                historyItem.text = '';
                _self.HistoryItems.push(historyItem);
            }
        });
    }

    /**
     * 展示日期轴
     * @param callback
     */
    this.showTimeLine = function (callback) {

        if ((_currentTimeIndex + 1) > _timeNum) {
            _currentTimeIndex = 0;
        }

        var timeLineHtml = '<ul class="timeline_list timeline_list3">';
        for (var i = 0; i < _timeNum; i++) {
            if (i == 0) {
                timeLineHtml = timeLineHtml + '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="time_text">' + _self.HistoryItems[i]["time"] + '</div></span></li>';
            } else {
                timeLineHtml = timeLineHtml + '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="time_text">' + _self.HistoryItems[i]["time"] + '</div></span></li>';
            }
        }
        timeLineHtml += '<li></li></ul>';

        var dom = $(timeLineHtml);
        $("#edit_times_list").html(dom);
        dom.find("li:eq(" + _currentTimeIndex + ")").find('div').addClass("time_text_active");
        dom.find("li:eq(" + _currentTimeIndex + ")").find('a').addClass("time_active");
        _self.showTime(_currentTimeIndex);

        var li_height = 50;
        dom.find("li").each(function (i) {
            $(this).click(function () {
                dom.find("li .timeline_circle").each(function (j) {
                    if (i == j) {
                        dom.find("li").find('div').removeClass("time_text_active");
                        dom.find("li").find('a').removeClass("time_active");

                        _self.saveCurrentTime(_currentTimeIndex);
                        _currentTimeIndex = i;

                        dom.find("li:eq(" + i + ")").find('div').addClass("time_text_active");
                        dom.find("li:eq(" + i + ")").find('a').addClass("time_active");

                        if (i != 0) {
                            dom.animate({"margin-top": -li_height * (j - 1) + "px"}, 200);
                        }
                        _self.showTime(_currentTimeIndex);
                    }
                });
            });
        });
    }

    /**
     * 保存当前编辑的时间点
     */
    this.saveCurrentTime = function (index) {
        if (index == null) {
            index = _currentTimeIndex;
        }
        _self.HistoryItems[index].title = $("#itemTitle").val();
        _self.HistoryItems[index].text = $("#itemText")[0].innerHTML;
    }

    /**
     * 读取数组展示已编辑的时间点
     */
    this.showTime = function (index) {
        if (_self.HistoryItems[index].img != '' && typeof _self.HistoryItems[index].img != 'undefined') {
            $("#selectHistoryImg").attr("src", _self.HistoryItems[index].img);
        } else {
            $("#selectHistoryImg").attr("src", '../../../images/btn_gallery_add.jpg');
        }
        $("#itemTitle").val(_self.HistoryItems[index].title);
        $("#itemText").html(_self.HistoryItems[index].text);

        $('#itemText').unbind('click');
        $(".add_time_img").unbind('click');
        _self.init();
    }


    /**
     * 选择图片
     */
    this.selectHistoryImg = function () {
        var options = {multiple: false, accept: "image/jpg, image/jpeg, image/bmp, image/gif, image/png"};
        DialogUtil.openFileDialog(options).done(function (filePath) {
            if (filePath.indexOf('#') >= 0) {
                _self.warmAlert(parent.COMMANDS.getErrorMsg(2021));
                return;
            }
            $("#selectHistoryImg").attr("src", filePath);
            _self.HistoryItems[_currentTimeIndex].img = filePath;
        });
    }

    this.setCmdText = function (cmd) {
        _self.HistoryItems.length = 0;
        for (var i = 0; i < cmd.items.length; i++) {
            var historyItem = new HistoryItem();
            historyItem.time = cmd.items[i].time;
            historyItem.img = cmd.items[i].img;
            historyItem.title = cmd.items[i].title;
            historyItem.text = cmd.items[i].text;
            _self.HistoryItems.push(historyItem);
        }
        _timeNum = cmd.items.length;
        $("#list_time").val(_timeNum);
        _self.chooseTimesNum(cmd.items.length);
        _self.showTime(0);
        $(".history_title").val(cmd.title);
    }

    this.isUEditorDlgShow = function (callback) {
        if (callback) {
            callback(_uEditorDlg);
        }
    }

    this.orientateHistory = function (index) {
        _currentTimeIndex = index;
        _self.showTimeLine();
        _self.showTime(index);
    }

    /**
     * 预览时间轴
     * @param timelineStyle
     */
    this.previewTime = function (timelineStyle) {

        $('#pre_history_title').html($(".history_title").val());
        if (timelineStyle === 'vertical') {
            $('#pre_history_x').hide();
            $('#pre_history_y').show();

            var timeLineHtml = '<ul class="timeline_list timeline_list3">';
            for (var i = 0; i < _timeNum; i++) {
                if (i == 0) {
                    timeLineHtml = timeLineHtml + '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="time_text">' + _self.HistoryItems[i]["time"] + '</div></span></li>';
                } else {
                    timeLineHtml = timeLineHtml + '<li><span class="timeline_circle"><a href="javascript:void(0)"></a><div class="time_text">' + _self.HistoryItems[i]["time"] + '</div></span></li>';
                }

            }
            timeLineHtml += '<li></li></ul>';

            $("#preview_times_list_y").html(timeLineHtml);
            $("#preview_times_list_y li:eq(0) div").addClass("time_text_active");
            $("#preview_times_list_y li:eq(0) a").addClass("time_active");

            $('#preview_first_img_y').attr('src', _self.HistoryItems[0]['img']);
            $('#preview_first_title_y').html(_self.HistoryItems[0]['title']);
            $('#preview_first_text_y').html(_self.HistoryItems[0]['text']);

        } else {
            $('#pre_history_x').show();
            $('#pre_history_y').hide();


            var timeLineHtml = '<ul style="margin-left: 40px">';
            for (var i = 0; i < _timeNum; i++) {
                if (i < 3) {
                    timeLineHtml = timeLineHtml + '<li style="float: left;width: 140px;position: relative;" class="timeline_circle"><span><a href="javascript:void(0)" style="margin-top: -25px;margin-left: 40px;"></a><div class="time_text" style="margin-left: -15px">' + _self.HistoryItems[i]["time"] + '</div></span></li>';
                }
            }
            timeLineHtml += '</ul>';


            $("#preview_times_list_x").html(timeLineHtml);
            $("#preview_times_list_x li:eq(0) div").addClass("time_text_active");
            $("#preview_times_list_x li:eq(0) a").addClass("time_active");

            $('#preview_first_img_x').attr('src', _self.HistoryItems[0]['img']);
            $('#preview_first_title_x').html(_self.HistoryItems[0]['title']);
            $('#preview_first_text_x').html(_self.HistoryItems[0]['text']);
        }


    }

    /**
     * 切换到选择时间轴数量页面
     */
    this.changeSelectTime = function (callback) {
        $("#edit_time").hide();
        $("#sel_time").show();
        $("#preview_time").hide();
    }

    /**
     * 切换到编辑时间轴页面
     */
    this.changeEditTime = function (callback) {
        $("#sel_time").hide();
        $("#edit_time").show();
        $("#preview_time").hide();
    }

    /**
     * 切换到预览页面
     */
    this.changPreviewTime = function () {
        $("#sel_time").hide();
        $("#edit_time").hide();
        $("#preview_time").show();
    }

    /**
     * 时间轴模板创建完成，将画廊信息写入json文件
     */
    this.getHistoryInfo = function (timeline_style, callback) {
        var _self = this;
        _self.getThumbImgCanvasData().done(function (thumbData) {
            var historyArrJson = [];
            for (var i = 0; i < _timeNum; i++) {
                //拷贝图片文件
                var url = _self.HistoryItems[i].img;
                var historyJson = {time: _self.HistoryItems[i].time, img: url, title: _self.HistoryItems[i].title, text: _self.HistoryItems[i].text};
                historyArrJson.push(historyJson);
            }

            var historyInfo = {"cardtype": "history", "thumbnail": 'thumbnail.jpg', "title": $(".history_title").val(), "style": timeline_style, "items": historyArrJson};

            if (callback) {
                callback(historyInfo, thumbData);
            }
        });
    }

    /**
     * 截取当前卡片的缩略图canvas
     */
    this.getThumbImgCanvasData = function () {
        var def = $.Deferred();
        if ($(".history_title").val() == "") {
            $(".history_title").hide();
        }
        if ($("#itemTitle").val() == "") {
            $("#itemTitle").val(" ");
        }
        if ($("#itemText")[0].innerHTML == "") {
            $("#itemText").html(" ");
        }
        html2canvas($("#body")[0], {
            onrendered: function (canvas) {
                var data = canvas.toDataURL('image/jpeg');
                $(".history_title").show();
                if ($("#itemTitle").val() == " ")$("#itemTitle").val("");
                if ($("#itemText")[0].innerHTML == " ")$("#itemText").html("");
                def.resolve(data);
            }
        });
        return def.promise();
    }

    /**
     * 温馨提示弹框
     * @param {string} info 提示语
     */
    this.warmAlert = function (info) {
        parent.COMMANDS.showSelectorPop(info, null, null, this, [
            {
                label: '确定',
                cssClass: 'btn-primary',
                action: function () {
                    parent.COMMANDS.hidePop();
                }}
        ]
        );
    }
}