define(function (require, exports, module) {
    function HistoryItem() {
        this.time;
        this.img;
        this.title;
        this.text;
    };

    function HistoryTemplate() {
    }

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

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

        $("#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());
            });
            _self._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 (e) {
            _self.saveCurrentTime(null);

            var _tar = $(this);
            $(_tar).off();
            var _content = _tar[0].innerHTML;
            $(_tar).html('');
            var editor = UE.getEditor(_tar[0].id,{
                initialFrameWidth:'100%',
                initialFrameHeight: '108',
                UEDITOR_HOME_URL:'share/assert/js/3rdparty/ueditor/'
            });

            var _textMask = $('<div id="ue_text_mask" class="ue-text-mask"></div>');
            $('#historyFrame').append(_textMask);
            editor.addListener('ready',function(e){
                editor.setContent(_content);
                _self._uEditorDlg = true;
                $(_tar).css('overflow','visible');
            })

            _textMask.on('click',function(e){
                $(this).remove();
                _content = editor.getContent();
                editor.destroy();

                _tar.html(_content);
                _self.HistoryItems[_self._currentTimeIndex].text = _content;
                _self.showTime(_self._currentTimeIndex);
            })
            editor.addListener('destroy',function(e){
                $(_tar).html(_content);
                $(_tar).css('overflow','auto');
                $(_tar).css('height','110px');

                _self._uEditorDlg = false;
            });
        });

        // 选择图片
        $(".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 时间节点个数
     */
    HistoryTemplate.chooseTimesNum = function (timeNum) {
        var _self = this;
        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();
    }

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

    HistoryTemplate.timeSortComplete = function (callback) {
        var _self = this;
        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);
        }
    }

    /**
     * 创建数组
     */
    HistoryTemplate.createTime = function (callback) {
        var _self = this;
        $(".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
     */
    HistoryTemplate.showTimeLine = function (callback) {
        var _self = this;

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

        var timeLineHtml = '<ul class="timeline_list timeline_list3">';
        for (var i = 0; i < _self._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(" + _self._currentTimeIndex + ")").find('div').addClass("time_text_active");
        dom.find("li:eq(" + _self._currentTimeIndex + ")").find('a').addClass("time_active");
        _self.showTime(_self._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(_self._currentTimeIndex);
                        _self._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(_self._currentTimeIndex);
                    }
                });
            });
        });
    }

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

    /**
     * 读取数组展示已编辑的时间点
     */
    HistoryTemplate.showTime = function (index) {
        var _self = this;
        if (_self.HistoryItems[index].img != '' && typeof _self.HistoryItems[index].img != 'undefined') {
            $("#selectHistoryImg").attr("src", _self.HistoryItems[index].img);
        } else {
            $("#selectHistoryImg").attr("src", './editor/assert/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();
    }

    /**
     * 选择图片
     */
    HistoryTemplate.selectHistoryImg = function () {
        var _self = this;
        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[_self._currentTimeIndex].img = filePath;
        });
    }

    HistoryTemplate.setCmdText = function (cmd) {
        var _self = this;
        _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);
        }
        _self._timeNum = cmd.items.length;
        $("#list_time").val(_self._timeNum);
        _self.chooseTimesNum(cmd.items.length);
        _self.showTime(0);
        $(".history_title").val(cmd.title);
    }

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

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

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

        $('#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 < _self._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: 20px;width: 560px;">';
            for (var i = 0; i < _self._timeNum; i++) {
                if (i < 4) {
                    timeLineHtml = timeLineHtml + '<li style="float: left;width: 140px;position: relative;" class="timeline_circle"><span><a href="javascript:void(0)" style="margin-top: -15px;margin-left: 20px;"></a><div class="time_text" style="margin-left: -4px;min-width: 100px;">' + _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']);
        }


    }

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

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

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

    /**
     * 时间轴模板创建完成，将画廊信息写入json文件
     */
    HistoryTemplate.getHistoryInfo = function (timeline_style, callback) {
        var _self = this;
        _self.getThumbImgCanvasData().done(function (thumbData) {
            var historyArrJson = [];
            for (var i = 0; i < _self._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
     */
    HistoryTemplate.getThumbImgCanvasData = function () {
        var def = $.Deferred();
        if ($(".history_title").val() == "") {
            $(".history_title").hide();
        }
        if ($("#itemTitle").val() == "") {
            $("#itemTitle").val(" ");
        }
        if ($("#itemText")[0].innerHTML == "") {
            $("#itemText").html(" ");
        }
        html2canvas($("#historyFrame")[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 提示语
     */
    HistoryTemplate.warmAlert = function (info) {
        parent.COMMANDS.showSelectorPop(info, null, null, this, [
            {
                label: '确定',
                cssClass: 'btn-primary',
                action: function () {
                    parent.COMMANDS.hidePop();
                }}
        ]
        );
    }
    exports.historyTemplate = HistoryTemplate;
});