/**
 * 习题--分类题模板处理
 * Created by hyt on 14-7-17.
 * @vision 1.0
 */
function PickCardItem() {
    this.title;
    this.answer;
};

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

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


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

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


    this.init = function () {

        $(".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));
            }
        });

        // 分类框名称限制
//        $(".card_title").bind('input propertychange', function(){
//            if(this.value.length>10) {
//                $(this).val($(this).val().substr(0, 10));
//            }
//        });

        // 分类题答案文字限制
//        $(".card_num").bind('input propertychange', function(){
//            if(this.value.length>8) {
//                $(this).val($(this).val().substr(0, 8));
//            }
//        });

        $("#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];
    }

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

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

        if (_self.pickCardItems.length > 0) {
            for (var i = 0; i < _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 < _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(_cardNum == 2){
            $("#pick_ul").css({"margin-top":"70px"});
        }else if(_cardNum == 3){
            $("#pick_ul").css({"margin-top":"50px"});
        }else{
            $("#pick_ul").css({"margin-top":"30px"});
        }
    }

    this.createPickCardItems = function () {
        for (var i = 0; i < _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);
            }
        }
    }

    this.showPickCardList = function () {

        var html = '<ul class="graph_list">';

        for (var i = 0; i < _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">' + _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 = $(_addCardHtml);
                hml.append(_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 = _globleId;
                                pick.type = 'text';
                                pick.value = $(this).val();
                                _self.pickCardOptions.push(pick);
                                _self.pickCardItems[index].answer.push(pick.id);
                                _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 = _globleId;
                            pick.type = 'img';
                            pick.value = imgPath;
                            _self.pickCardOptions.push(pick);
                            _self.pickCardItems[index].answer.push(pick.id);
                            _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();
                });
            }
        });
    }

    this.selectImg = function () {
        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();
    }

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

    this.getPickCardInfo = function (callback) {
        _self.getThumbImgCanvasData().done(function (thumbData) {
            var PickCardItem = [];
            var PickCardOption = [];
            for(var i = 0;i < _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":_globleId, "cardtype": "pickcard", "thumbnail": 'thumbnail.jpg', "style": "horizon", "title": $(".pick_title").val(), "items": PickCardItem, 'options': PickCardOption};
            if (callback) {
                callback(pickcardInfo, thumbData);
            }
        });
    }

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

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

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

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

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

    this.previewPickcard = function () {
        $("#preview_card_title").html($(".pick_title").val());
        var card_html = '';
        var answer_html = ''
        for (var i = 0; i < _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(_cardNum == 2){
            $('#preview_pickcard_ul').css({'margin-left':'120px'});
        }
        if(_cardNum == 3){
            $('#preview_pickcard_ul').css({'margin-left':'65px'});
        }
        $('#preview_pickcard_ul').html(card_html);
        $('#preview_pickcard_answers').html(answer_html);
    }

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