/**
 * 画廊卡片模板功能类
 * Date: 2014/06/30
 * Author: luxing@iflytek.com
 * @version 1.0
 * @module gallerycardtemplate
 */
define(function (require, exports, module) {

    function GalleryContext() {
        this.ClickToAddTittle = "点击此处添加标题";
        this.ClickToAddDescription = "点击此处添加描述";
    }

    function GalleryItem() {
        this.title;
        this.description;
        this.url;
    };

    function GalleryCardTemplate() {}


    /**
     * 初始化画廊卡片模板
     */
    GalleryCardTemplate.init = function () {
        var _self = this;

        /**
         * 画廊卡片模板界面按钮列表
         * @type {{galleryTmpEditBtn: (*|jQuery|HTMLElement), closeBtnGalleryTmpPanel: (*|jQuery|HTMLElement), galleryImgBtnExt: (*|jQuery|HTMLElement), galleryImgBtn: (*|jQuery|HTMLElement), galleryDeleteBtn: (*|jQuery|HTMLElement), addImgBtn: (*|jQuery|HTMLElement), galleryCompleteBtn: (*|jQuery|HTMLElement)}}
         */
        this.buttons = {
            galleryTmpEditBtn: $("#galleryTmpEditBtn"),
            closeBtnGalleryTmpPanel: $("#closeBtn_galleryTmpPanel"),
            galleryImgBtnExt: $("#galleryImgBtnExt"),
            galleryImgBtn: $("#galleryImgBtn"),
            galleryDeleteBtn: $("#galleryDeleteBtn"),
            addImgBtn: $("#addImgBtn"),
            galleryCompleteBtn: $("#galleryCompleteBtn")
        };

        /**
         * 画廊卡片模板界面控件列表
         * @type {{galleryTmpPanel: (*|jQuery|HTMLElement), galleryTmpPanelTop: (*|jQuery|HTMLElement), galleryTmpPanelMask: (*|jQuery|HTMLElement), deleteBtnPanel: (*|jQuery|HTMLElement), galleryTitle: (*|jQuery|HTMLElement), galleryDescription: (*|jQuery|HTMLElement), galleryPagePanel: (*|jQuery|HTMLElement), imgSortPanel: (*|jQuery|HTMLElement), galleryEditPanel: (*|jQuery|HTMLElement)}}
         */
        this.controls = {
            galleryTmpPanel: $("#galleryTmpPanel"),
            galleryTmpPanelTop: $("#galleryTmpPanelTop"),
            galleryTmpPanelMask: $("#galleryTmpPanelMask"),
            galleryTitle: $("#galleryTitle"),
            galleryDescription: $("#galleryDescription"),
            galleryPagePanel: $("#galleryPagePanel"),
            imgSortPanel: $("#imgSortPanel"),
            galleryEditPanel: $("#galleryEditPanel")
        };

        /**
         * 存放画廊图片信息的数据结构
         * @type {Array}
         */
        this.GalleryItems = [];

        /**
         * 画廊中焦点显示图片的位置
         * @type {number}
         */
        this.GalleryPos = 0;


        //点击图片区选择图片
        $("#galleryImgBtn").click(function () {
            //只有当画廊图片数为零时，点击#galleryImgBtn才会弹出图片对话框
            if (_self.GalleryItems.length == 0)
                _self.selectGalleryImg();
        });

        //图片描述过长则截断处理
        $("#galleryDescription").bind('input propertychange', function () {
            if (_self.GalleryItems.length > 0) {
                var desLengthArr = _calcStrLength(this.value);
                var desStrLength = desLengthArr[0];
                var mostIndex = desLengthArr[1];
                if (desStrLength > 65) {
                    //过长，截断处理
                    this.value = this.value.substr(0, mostIndex + 1);
                }
                _self.GalleryItems[_self.GalleryPos - 1].description = this.value;
            } else {
                this.value = "";
            }
        });

        //标题过长则截断处理
        $("#galleryTitle").bind('input propertychange', function () {
            var titleLengthArr = _calcStrLength(this.value);
            var titleStrLength = titleLengthArr[0];
            var mostIndex = titleLengthArr[1];
            if (titleStrLength > 65) {
                //标题过长，截断处理
                this.value = this.value.substr(0, mostIndex + 1);
            }
        });

        //计算标题整体字符所占长度
        function _calcStrLength(str) {
            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 < 65) {
                    mostIndex = i;
                }
            }
            return [len, mostIndex];
        }

        //图片拖动排序
        $("#imgSortList").dragsort({ dragSelector: "div", dragBetween: true, dragEnd: saveOrder, placeHolderTemplate: "<li class='placeHolder'><div></div></li>" });
        function saveOrder() {
            //先把数字顺序重置
            var spans = $("#imgSortList").find("span");
            for (var i = 0; i < spans.length; i++) {
                spans[i].innerHTML = i + 1;
            }
            var data = $("#imgSortList li").map(function () {
                return $(this).children().html();
            }).get();
            $("input[name=listSortOrder]").val(data.join("|"));
        }

        //修复拖到边缘后点击完成的bug
        $("#imgSortPanel").mouseout(function () {
            $(document).mouseup();
        });
    };

    /**
     * 加载编辑已存在的画廊卡片
     * @param {object} galleryInfo 卡片资源的地址
     */
    GalleryCardTemplate.loadGallery = function (galleryInfo) {
        var _self = this;
        var galleryImages = galleryInfo.images;
        console.log("%c galleryInfo %o", "color:green", galleryImages);
        for (var i = 0; i < galleryImages.length; i++) {
            var galleryItem = new GalleryItem();
            galleryItem.title = galleryInfo.title;
            _self.controls.galleryTitle.val(galleryInfo.title);
            galleryItem.description = galleryImages[i].des;
            galleryItem.url = galleryImages[i].src;
            _self.GalleryItems.push(galleryItem);
        }
        _self.refreshGallery(1);
    }

    /**
     *选择图片上传
     */
    GalleryCardTemplate.selectGalleryImg = function () {
        var _self = this;
        var lastImgIndex = _self.GalleryItems.length;
        var options = {multiple: true, accept: "image/jpg, image/jpeg, image/bmp, image/gif, image/png"};
        DialogUtil.openFileDialog(options).done(function (filePaths) {
            var sharpIndex = filePaths.indexOf("#");
            if (sharpIndex != -1) {
                _self.warmAlert("您添加的文件名称或所在文件夹名称中存在特殊字符，请修改后重试");
                return;
            }
            filePaths = filePaths.replace(/;(.:)/g, "|$1");
            filePaths = filePaths.split("|");
            var imgNum = filePaths.length + _self.GalleryItems.length;
            //限制最多添加10张照片,超过10张则添加图片数够10就行
            if (imgNum > 10) {
                _self.warmAlert('最多只能添加10张图片');
                var canAddNum = 10 - _self.GalleryItems.length;
                filePaths.length = canAddNum > 0 ? canAddNum : 0;
            }

            for (var i = 0; i < filePaths.length; i++) {
                var galleryImgItem = new GalleryItem();
                galleryImgItem.url = filePaths[i];
                galleryImgItem.title = $("#galleryTitle").attr("value");
                galleryImgItem.description = GalleryContext.ClickToAddDescription;
                _self.GalleryItems.push(galleryImgItem);
            }
            var tempItem = _self.GalleryItems[0];
            var str = tempItem.url;
            _self.buttons.galleryImgBtn.attr("src", str);
            _self.buttons.galleryImgBtn.css("cursor", "auto");
            if (lastImgIndex > 0 && lastImgIndex < _self.GalleryItems.length) {
                _self.refreshGallery(lastImgIndex + 1);
            } else {
                _self.refreshGallery(1);
            }

        });
    };

    /**
     *删除画廊图片
     * @param page 待删除图片的序号
     */
    GalleryCardTemplate.deleteGalleryImg = function () {
        var _self = this;
        var page = _self.GalleryPos;
        _self.GalleryItems.splice(page - 1, 1);

        var length = _self.GalleryItems.length;
        if (length === 0) {
            _self.buttons.galleryImgBtn.attr("src", "gallery_img.png");
            _self.buttons.galleryImgBtn.css("cursor", "pointer");
            _self.GalleryPos = 0;
            _self.refreshGallery(0);
        }
        else if (length > 0) {
            if (page == 1) {               //第1张图片
                _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[0].url);
                _self.buttons.galleryImgBtn.css("cursor", "auto");
                _self.GalleryPos = page;
                _self.refreshGallery(page);
            } else if (page == length + 1) { //最后一张图片
                _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[length - 1].url);
                _self.buttons.galleryImgBtn.css("cursor", "auto");
                _self.GalleryPos = length;
                _self.refreshGallery(length);
            } else {                      //中间图片
                _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[page - 1].url);
                _self.buttons.galleryImgBtn.css("cursor", "auto");
                _self.GalleryPos = page;
                _self.refreshGallery(page);
            }
        }
    }

    /**
     * 更新画廊信息，根据画廊图片列表信息，决定画廊面板界面
     * @param page 待显示图片的序号
     */
    GalleryCardTemplate.refreshGallery = function (page) {
        var _self = this;
        //更新图片描述信息
        if (page > 0) {
            _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[page - 1].url);
            _self.buttons.galleryImgBtn.css("cursor", "auto");
            _self.controls.galleryDescription.val(_self.GalleryItems[page - 1].description);
            parent.document.getElementById("btnDeleteCurImg").style.display = "inline-block";
            parent.document.getElementById("btnImgSort").style.display = "inline-block";
            parent.document.getElementById("btnFinish").style.display = "inline-block";
        } else {
            _self.buttons.galleryImgBtn.attr("src", "gallery_img.png");
            _self.buttons.galleryImgBtn.css("cursor", "pointer");
            _self.controls.galleryDescription.val("");
            parent.document.getElementById("btnDeleteCurImg").style.display = "none";
            parent.document.getElementById("btnImgSort").style.display = "none";
            parent.document.getElementById("btnFinish").style.display = "none";
        }

        //根据画廊图片个数决定galleryPagePanel的界面
        _self.controls.galleryPagePanel.html("");
        var index = 0;
        for (var i = 0; i < _self.GalleryItems.length; i++) {
            var btn = $("<input/>");
            btn.attr("type", "button");
            btn.attr("class", "btn_flip");
            btn.css({"margin": "5px", "width": "25px", "height": "25px", "padding": "0px"});
            if (page === i + 1) {
                btn.removeClass();
                btn.addClass("btn_flip2");
            }
            else {
                btn.removeClass();
                btn.addClass("btn_flip");
                //btn.mousedown(function () {
                //    $(this).removeClass();
                //    $(this).addClass("btn_flip2");
                //});
            }
            btn.val(i + 1);
            btn.click(function () {
                var val = $(this).val();
                var index = parseInt(val - 1);
                _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[index].url);
                _self.buttons.galleryImgBtn.css("cursor", "auto");
                _self.controls.galleryDescription.val(_self.GalleryItems[index].description);
                console.log(_self.GalleryItems[index].description);
                _self.GalleryPos = parseInt(val);//更新焦点图片
                _self.refreshGallery(parseInt(val));
                $(this).removeClass();
                $(this).addClass("btn_flip2");
            });
            _self.controls.galleryPagePanel.append(btn);
        }

        _self.GalleryPos = page;
    };


    /**
     * 画廊图片排序
     */
    GalleryCardTemplate.imgSort = function () {
        var _self = this;
        //弹出图片排序界面
        _self.controls.galleryEditPanel.hide();
        _self.controls.imgSortPanel.show();
        //清空#imgSortList中的子元素,删除图片或者添加图片后继续排序将重新获取子元素
        $("#imgSortList").html("");
        //获得图片列表
        for (var i = 0; i < _self.GalleryItems.length; i++) {
            var li = $("<li style='float: left'>");
            var div = $("<div>");
            var img = $("<img/>");
            var des = $("<span>" + (i + 1) + "</span>")
            img.attr({"src": _self.GalleryItems[i].url, "alt": _self.GalleryItems[i].description, "style": "height: 78px; width: 95px;"});
            div.append(img);
            div.append(des);
            li.append(div);
            $("#imgSortList").append(li);
        }
    };

    /**
     * 画廊图片排序完成
     */
    GalleryCardTemplate.imgSortComplete = function () {
        var _self = this;
        //根据图片排序结果更新画廊图片数组数据
        $("#imgSortList").find("span").remove();
        //清空数组
        _self.GalleryItems.length = 0;
        //对数组重新赋值
        $("#imgSortList>li").each(function () {
            var item = new GalleryItem();
            item.title = _self.controls.galleryTitle.val();
            //获取<li>中的子元素<div>
            $(this).children().each(function () {
                $(this).children().each(function () {
                    //获取<div>中的子元素<img>
                    item.url = $(this).attr("src");
                    item.description = $(this).attr("alt");
                });
            });
            _self.GalleryItems.push(item);
        });
        _self.controls.galleryEditPanel.show();
        _self.controls.imgSortPanel.hide();
        //转到画廊添加编辑界面，更新焦点图片和图片描述
        _self.buttons.galleryImgBtn.attr("src", _self.GalleryItems[_self.GalleryPos - 1].url);
        _self.buttons.galleryImgBtn.css("cursor", "auto");
        _self.controls.galleryDescription.val(_self.GalleryItems[_self.GalleryPos - 1].description);
        _self.refreshGallery(1);
    };

    /**
     * 画廊卡片模板创建完成，将画廊信息写入json文件
     */
    GalleryCardTemplate.getGalleryInfo = function (callback) {
        var _self = this;
        if (_self.GalleryItems.length < 1) {
            return;
        }
        _self.getThumbImgCanvasData().done(function (thumbData) {
            var imgArrJson = [];
            for (var i = 0; i < _self.GalleryItems.length; i++) {
                //拷贝图片文件
                if (_self.GalleryItems[i].description == GalleryContext.ClickToAddDescription)
                    _self.GalleryItems[i].description = "";
                var url = _self.GalleryItems[i].url;
                //url = url.substring(url.lastIndexOf("\\")+1);
                var imgJson = {src: url, des: _self.GalleryItems[i].description, index: i.toString()};
                imgArrJson.push(imgJson);
            }
            var galleryInfo = {"cardtype": "gallery", "thumbnail": 'thumbnail.png', "title": _self.controls.galleryTitle.val(), "keywords": 'test', "images": imgArrJson};
            if (callback) {
                callback(galleryInfo, thumbData);
            }
        });
    };

    /**
     * 截取当前卡片的缩略图canvas
     */
    GalleryCardTemplate.getThumbImgCanvasData = function () {
        var _self = this;
        _self.refreshGallery(1);
        var def = $.Deferred();
        $("#galleryTitle").parent('div').css({
            'height': '40px',
            'width': '598px',
            'margin-left': '-12px',
            'background': '-webkit-linear-gradient(top, #f9f9f9, #e7e7e7)',
            'border-bottom': '1px solid #a6a7a6'
        });
        $("#galleryTitle").css({
            'border': '0',
            'width': '598px',
            'background': '-webkit-linear-gradient(top, #f9f9f9, #e7e7e7)',
            'font-size':'18px',
            'font-weight': 'bold',
            'font-family': 'microsoft yahei',
            'color': '#222',
            'text-overflow': 'ellipsis',
            'white-space': 'nowrap',
            'overflow': 'hidden'
        });

        $("#galleryDescription").css("border", "0px");
        $("#galleryImgBtnExt").css("border", "0px");
        if ($("#galleryTitle").val() == GalleryContext.ClickToAddTittle || $("#galleryTitle").val() == "") {
            $("#galleryTitle").val(" ");
        }
        if ($("#galleryDescription").val() == GalleryContext.ClickToAddDescription || $("#galleryDescription").val() == "") {
            $("#galleryDescription").val(" ");
        }

        html2canvas($("#galleryContainer")[0], {
            onrendered: function (canvas) {
                var data = canvas.toDataURL();
                //console.log(data);
                def.resolve(data);
                $("#galleryTitle").show();
                $("#galleryDescription").show();
                $("galleryPagePanel").show();
            }
        });
        return def.promise();
    }

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

    exports.galleryCardTemplate = GalleryCardTemplate;
});



