define(function (require, exports, module) {

    function PickCardItem() {
        this.title;
        this.answer;
    };

    function PickCardOption() {
        this.id;
        this.type; // text/img
        this.value;
    }

    function PickCardTemplate() {
    }

    PickCardTemplate.initDatas = function () {
        this._cardNum = 4;
        this._currentIndex = 0;
        this._globleId = 1;
        this._carNameTmp = [];
        this.pickCardItems = [];
        this.pickCardOptions = [];

        this._addCardHtml = '<span class="graph_list_group">' +
            '<a href="javascript:;" class="graph_list_text" title="文字">' +
            '<img src="editor/assert/js/widget/pickcard/graph_list_text.png" alt=""></a>' +
            '<a href="javascript:;" class="graph_list_img" title="图片">' +
            '<img src="editor/assert/js/widget/pickcard/graph_list_img.png" alt=""></a></span>';

        this._delCardHtml = '<a href="javascript:;" class="graph_list_close" style="display: none"></a>';
    }


    PickCardTemplate.init = function () {
        var _self = this;

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

        // 分类题标题限制
        $(".pick_title").unbind('input propertychange');
        $(".pick_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));
            }
        });

        $("#selCardNum").unbind('change');
        $("#selCardNum").change(function () {
            _self._carNameTmp = [];
            $(".card_title").each(function (i) {
                if (_self.pickCardItems.length > i) {
                    _self.pickCardItems[i].title = $(this).val();
                }
                _self._carNameTmp.push($(this).val());
            });
            _self.chooseCardNum();
            _self.showSelectCardNum();
        });

    }

    //计算标题整体字符所占长度
    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];
    }

    PickCardTemplate.chooseCardNum = function () {
        var _self = this;
        _self._cardNum = parseInt($("#selCardNum").val());
    }

    PickCardTemplate.showSelectCardNum = function () {
        var _self = this;
        $("#pick_ul").empty();

        if (_self.pickCardItems.length > 0) {
            for (var i = 0; i < _self._cardNum; i++) {
                if (i < _self.pickCardItems.length) {
                    $("#pick_ul").append($('<li>分类框：<input type="text" class="add_answer add_answer2 card_title" value="' + _self.pickCardItems[i].title + '" placeholder="请输入分类框名称"/>' +
                        '</li>'));
                } else {
                    $("#pick_ul").append($('<li>分类框：<input type="text" class="add_answer add_answer2 card_title" placeholder="请输入分类框名称"/>' +
                        '</li>'));
                }
            }
        } else {
            for (var i = 0; i < _self._cardNum; i++) {
                if (i < _self._carNameTmp.length) {
                    $("#pick_ul").append($('<li>分类框：<input type="text" class="add_answer add_answer2 card_title" value="' + _self._carNameTmp[i] + '" placeholder="请输入分类框名称"/>' +
                        '</li>'));
                } else {
                    $("#pick_ul").append($('<li>分类框：<input type="text" class="add_answer add_answer2 card_title" placeholder="请输入分类框名称"/>' +
                        '</li>'));
                }
            }
        }
        _self.init();// 绑定事件
        if (_self._cardNum == 2) {
            $("#pick_ul").css({"margin-top": "70px"});
        } else if (_self._cardNum == 3) {
            $("#pick_ul").css({"margin-top": "50px"});
        } else {
            $("#pick_ul").css({"margin-top": "30px"});
        }
    }

    PickCardTemplate.createPickCardItems = function () {
        var _self = this;
        for (var i = 0; i < _self._cardNum; i++) {
            if (_self.pickCardItems.length > 0) {
                if (i >= _self.pickCardItems.length) {
                    var pickCardItem = new PickCardItem();
                    pickCardItem.title = $(".card_title:eq(" + i + ")").val();
                    pickCardItem.answer = [];
                    _self.pickCardItems.push(pickCardItem);
                } else {
                    _self.pickCardItems[i].title = $(".card_title:eq(" + i + ")").val();
                }
            } else {
                var pickCardItem = new PickCardItem();
                pickCardItem.title = $(".card_title:eq(" + i + ")").val();
                pickCardItem.answer = [];
                _self.pickCardItems.push(pickCardItem);
            }
        }
    }

    PickCardTemplate.showPickCardList = function () {
        var _self = this;
        var html = '<ul class="graph_list">';

        for (var i = 0; i < _self._cardNum; i++) {
            html += '<li><p>' + _self.pickCardItems[i].title + '</p><ul class="graph_list_sun clearfix">'
            if (_self.pickCardItems.length > 0) {
                for (var j = 0; j < _self.pickCardItems[i].answer.length; j++) {
                    var id = _self.pickCardItems[i].answer[j];
                    for (var k = 0; k < _self.pickCardOptions.length; k++) {
                        if (id === _self.pickCardOptions[k].id) {
                            html += '<li class="card_li">' + _self._delCardHtml;
                            if (_self.pickCardOptions[k].type === 'img') {
                                html += '<img src="' + _self.pickCardOptions[k].value + '"/>';
                            } else {
                                html += '<input type="text" value="' + _self.pickCardOptions[k].value + '" style="width: 81px;height:65px;border:none;text-align: center;" class="card_num" placeholder="请输入"/>';
                            }
                            html += '</li>';
                        }
                    }
                }
            }
            if (_self.pickCardItems[i].answer.length > 3) {
                html += '<li style="display: none"><a href="javascript:;" title="新增答案" index="' + i + '" class="graph_list_add"></a></li></ul></li>';
            } else {
                html += '<li><a href="javascript:;" title="新增答案" index="' + i + '" class="graph_list_add"></a></li></ul></li>';
            }
        }

        html += '</ul>'
        var dom = $(html);
        dom.find(".graph_list_close").hide();
        $("#pickcard_eidt").html(dom);
        _self.init();

        // 编辑
        dom.find(".graph_list_close").click(function () {
            var index = $(this).parents("li").parents("ul").parents("li").index();
            var li_index = $(this).parents("li").index();

            _self.deleteCard(index, li_index);
            $(this).parent("li").parent("ul").find(".graph_list_add").parent('li').show();
            $(this).parent("li").remove();
        });

        dom.find(".card_li").mouseover(function () {
            $(this).find(".graph_list_close").show();
        });

        dom.find(".card_li").mouseleave(function () {
            $(this).find(".graph_list_close").hide();
        });

        dom.find("input").focusout(function () {
            var index = parseInt($(this).parents("li").find(".graph_list_add").attr("index"));
            var li_index = $(this).parents("li").index();
            var id = _self.pickCardItems[index].answer[li_index];
            for (var i = 0; i < _self.pickCardOptions.length; i++) {
                if (id === _self.pickCardOptions[i].id) {
                    _self.pickCardOptions[i].value = $(this).val();
                    break;
                }
            }
        });

        // 新增
        dom.find(".graph_list_add").click(function () {

            if (_self.pickCardItems[parseInt($(this).attr("index"))].answer.length < $(this).parents('li').index()) {
                return;
            }

            if ($(this).parents("li").index() <= 3) {

                if ($(this).parent("li").index() === 3) {
                    $(this).parent("li").hide();
                }

                var index = parseInt($(this).attr("index"));
                var hml = $('<li></li>');
                $(this).parent("li").before(hml);

                var h = $(_self._addCardHtml);
                hml.append(_self._delCardHtml);
                hml.append(h);

                hml.mouseover(function () {
                    $(this).find(".graph_list_close").show();
                });

                hml.mouseleave(function () {
                    $(this).find(".graph_list_close").hide();
                });

                // 输入文字
                h.find(".graph_list_text").click(function () {
                    var li_index = $(this).parents("span").parents("li").index();
                    hml.find("span").remove();
                    var input_dom = $('<input type="text" style="width: 81px;height:65px;border:none;text-align: center;" class="card_num" placeholder="请输入"/>');
                    hml.append(input_dom);
                    _self.init();

                    input_dom.focus();

                    hml.find("input").focusout(function () {
                        if ($(this).val()) {
                            if (_self.pickCardItems[index].answer[li_index]) {
                                var id = _self.pickCardItems[index].answer[li_index];
                                for (var i = 0; i < _self.pickCardOptions.length; i++) {
                                    if (id == _self.pickCardOptions[i].id) {
                                        _self.pickCardOptions[i].value = $(this).val();
                                        break;
                                    }
                                }
                            } else {
                                var pick = new PickCardOption();
                                pick.id = _self._globleId;
                                pick.type = 'text';
                                pick.value = $(this).val();
                                _self.pickCardOptions.push(pick);
                                _self.pickCardItems[index].answer.push(pick.id);
                                _self._globleId++;
                            }
                        } else {
                            _self.deleteCard(index, li_index);
                        }
                    });
                });

                // 选择图片
                h.find(".graph_list_img").click(function () {
                    var li_index = $(this).parents("span").parents("li").index();
                    _self.selectImg().done(function (imgPath) {
                        if (imgPath != '' && imgPath != null) {
                            hml.find("span").remove();
                            hml.append('<img src="' + imgPath + '"/>');
                            hml.find('.graph_list_close').hide();
                            var pick = new PickCardOption();
                            pick.id = _self._globleId;
                            pick.type = 'img';
                            pick.value = imgPath;
                            _self.pickCardOptions.push(pick);
                            _self.pickCardItems[index].answer.push(pick.id);
                            _self._globleId++;
                        }
                    });

                });

                // 删除操作
                hml.find(".graph_list_close").click(function () {
                    var li_index = $(this).parents("li").index();

                    _self.deleteCard(index, li_index);
                    $(this).parents("li").find(".graph_list_add").parent("li").show();
                    hml.remove();
                });
            }
        });
    }

    PickCardTemplate.selectImg = function () {
        var _self = this;
        var def = $.Deferred();
        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) {
                filePath = null;
                _self.warmAlert(parent.COMMANDS.getErrorMsg(2021));
            }
            def.resolve(filePath);
        });
        return def.promise();
    }

    PickCardTemplate.deleteCard = function (row, col) {
        var _self = this;
        _self.pickCardItems[row].answer.splice(col, 1);
    }

    PickCardTemplate.getPickCardInfo = function (callback) {
        var _self = this;
        _self.getThumbImgCanvasData().done(function (thumbData) {
            var PickCardItem = [];
            var PickCardOption = [];
            for (var i = 0; i < _self._cardNum; i++) {
                PickCardItem.push(_self.pickCardItems[i]);
                for (var j = 0; j < _self.pickCardItems[i].answer.length; j++) {
                    var id = _self.pickCardItems[i].answer[j];
                    for (var k = 0; k < _self.pickCardOptions.length; k++) {
                        if (_self.pickCardOptions[k].id === id) {
                            PickCardOption.push(_self.pickCardOptions[k]);
                            break;
                        }
                    }
                }
            }
            var pickcardInfo = {"maxid": _self._globleId, "cardtype": "pickcard", "thumbnail": 'thumbnail.jpg', "style": "horizon", "title": $(".pick_title").val(), "items": PickCardItem, 'options': PickCardOption};
            if (callback) {
                callback(pickcardInfo, thumbData);
            }
        });
    }

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

    PickCardTemplate.setCmdText = function (cmd) {
        var _self = this;
        _self.pickCardItems = cmd.items;
        _self.pickCardOptions = cmd.options;
        _self._cardNum = cmd.items.length;
        _self._globleId = cmd.maxid + 1;
        ;
        $("#selCardNum").val(_self._cardNum);
        $(".pick_title").val(cmd.title);
        _self.showSelectCardNum();
    }

    PickCardTemplate.showSelectPickCard = function () {
        $("#edit_pickcard").hide();
        $("#sel_pickcard").show();
        $("#preview_pickcard").hide();
    }

    PickCardTemplate.showEditPickCard = function () {
        $("#sel_pickcard").hide();
        $("#edit_pickcard").show();
        $("#preview_pickcard").hide();
    }

    PickCardTemplate.showPreviewPickCard = function () {
        $("#sel_pickcard").hide();
        $("#edit_pickcard").hide();
        $("#preview_pickcard").show();
    }

    PickCardTemplate.previewPickcard = function () {
        var _self = this;
        $("#preview_card_title").html($(".pick_title").val());
        var card_html = '';
        var answer_html = ''
        for (var i = 0; i < _self._cardNum; i++) {
            card_html += '<li class="li_card_box"><span>' + _self.pickCardItems[i].title + '</span><ul>';
            for (var j = 0; j < _self.pickCardItems[i].answer.length; j++) {
                var id = _self.pickCardItems[i].answer[j];
                for (var k = 0; k < _self.pickCardOptions.length; k++) {
                    if (id === _self.pickCardOptions[k].id) {
                        answer_html += '<li>';
                        if (_self.pickCardOptions[k].type === 'img') {
                            answer_html += '<img src="' + _self.pickCardOptions[k].value + '"/>';
                        } else {
                            answer_html += _self.pickCardOptions[k].value;
                        }
                        answer_html += '</li>';
                    }
                }
            }
            card_html += '</ul></li>'
        }
        if (_self._cardNum == 2) {
            $('#preview_pickcard_ul').css({'margin-left': '120px'});
        }
        if (_self._cardNum == 3) {
            $('#preview_pickcard_ul').css({'margin-left': '65px'});
        }
        $('#preview_pickcard_ul').html(card_html);
        $('#preview_pickcard_answers').html(answer_html);
    }

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