/**
 * 连线题编辑模板
 * Created by hyt on 14-9-12.
 * @vision 1.0
 */
function MatchCardItem() {
    this.id;  // q1 a1 q2 a2
    this.type;
    this.value;
};


function MatchcardTemplate() {
    var _self = this;
    var _cardNum = 4;
    var _currentIndex = 0;
    var _maxId = 0;
    this.MatchCardQues = []; // 连线题左边 问题 (打乱前)
    this.MatchCardAnsw = []; // 连线题右边 答案 (打乱前)

    this.Mcq = []; // 连线题左边 问题 (打乱后)
    this.Mca = []; // 连线题右边 答案 (打乱后)

    this.isRandom = false; // 是否随机排序

    this.popHtml = '<div style="display: none" class="lxt_edit_box">' +
        '<a href="javascript:void(0);" class="lxt_edit_text" title="文字"><i></i>文字</a>' +
        '<a href="javascript:void(0);" class="lxt_edit_img" title="图片"><i></i>图片</a>' +
        '</div>';

    this._delHtml = '<a style="display: none;" href="javascript:void(0);" class="graph_list_close"></a>';

    /**
     * 初始化绑定
     */
    this.init = function () {
        $("#list_num").unbind('change');
        $("#list_num").change(function () {
            _self.changeCardNum();
            _self.createMatchCardArray();
            _self.showEditCardList();
        });

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

        $(".match_title").unbind('input propertychange');
        // 连线题标题限制
        $(".match_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));
            }
        });

        // TODO:拖动排序
//        $("#card_question_ul ul").dragsort({ dragSelector: "li", dragBetween: true, dragEnd:saveQuestionOrder, placeHolderTemplate: "<li></li>" });
//        function saveQuestionOrder() {
//
//        }
//        $("#card_answer_ul ul").dragsort({ dragSelector: "li", dragBetween: true, dragEnd:saveAnswerOrder, placeHolderTemplate: "<li></li>" });
//        function saveAnswerOrder() {
//
//        }

        $('#card_question_ul li').unbind('mouseover');
        $('#card_question_ul li').mouseover(function (e) {
            var index = $(this).index();
            if(_self.MatchCardQues[index].type !== ''){
                $(this).find('a.graph_list_close').fadeIn(100);
            }
            $(this).find('.lxt_add').fadeOut(0);
            $(this).find('.lxt_edit_box').fadeIn(100);
        });

        $('#card_answer_ul li').unbind('mouseover');
        $('#card_answer_ul li').mouseover(function (e) {
            var index = $(this).index();
            if(_self.MatchCardAnsw[index].type !== ''){
                $(this).find('a.graph_list_close').fadeIn(100);
            }
            $(this).find('.lxt_add').fadeOut(0);
            $(this).find('.lxt_edit_box').fadeIn(100);
        });

        $('#card_question_ul li').unbind('mouseleave');
        $('#card_question_ul li').mouseleave(function () {
            $(this).find('.lxt_edit_box').fadeOut(100);
            var index = $(this).index();
            var text = $(this).find('textarea').val();
            if (text != '' && text != null) {
                _self.MatchCardQues[index].type = 'text';
                _self.MatchCardQues[index].value = text;
            }
            _self.showEditCardList();
        });

        $('#card_answer_ul li').unbind('mouseleave');
        $('#card_answer_ul li').mouseleave(function () {
            $(this).find('.lxt_edit_box').fadeOut(100);
            var index = $(this).index();
            var text = $(this).find('textarea').val();
            if (text != '' && text != null) {
                _self.MatchCardAnsw[index].type = 'text';
                _self.MatchCardAnsw[index].value = text;
            }
            _self.showEditCardList();
        });

    }

    //计算标题整体字符所占长度
    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.changeCardNum = function () {
        _cardNum = parseInt($("#list_num option:selected").val());
        if (_currentIndex >= _cardNum) {
            _currentIndex = 0;
        }
    }

    /**
     * 展现编辑页面
     */
    this.showEditCardList = function () {
        var queshtml = '<ul class="lxt_temp_ul2 clearfix">';
        var answhtml = '<ul class="lxt_temp_ul2 clearfix">';
        var linehtml = '';
        for (var i = 0; i < _cardNum; i++) {
            // 左侧列表
            if (_self.MatchCardQues[i].type === 'img') {
                queshtml += '<li class="lxt_edit"><img src="' + _self.MatchCardQues[i].value + '">'+_self._delHtml+'<em class="lxt_ic asb_r"></em></li>';
            } else if (_self.MatchCardQues[i].type === 'text') {
                queshtml += '<li class="lxt_edit"><textarea class="lxt_edit_input" placeholder="请输入文字">' + _self.MatchCardQues[i].value + '</textarea>'+_self._delHtml+'<em class="lxt_ic asb_r"></em></li>';
            } else {
                queshtml += '<li class="lxt_edit"><a href="javascript:void(0);" class="lxt_add" title="添加"></a>' + _self.popHtml + '<em class="lxt_ic asb_r"></em></li>';
            }
            // 右侧列表
            if (_self.MatchCardAnsw[i].type === 'img') {
                answhtml += '<li class="lxt_edit"><img src="' + _self.MatchCardAnsw[i].value + '">'+_self._delHtml+'<em class="lxt_ic asb_l"></em></li>';
            } else if (_self.MatchCardAnsw[i].type === 'text') {
                answhtml += '<li class="lxt_edit"><textarea class="lxt_edit_input" placeholder="请输入文字">' + _self.MatchCardAnsw[i].value + '</textarea>'+_self._delHtml+'<em class="lxt_ic asb_l"></em></li>';
            } else {
                answhtml += '<li class="lxt_edit"><a href="javascript:void(0);" class="lxt_add" title="添加"></a>' + _self.popHtml + '<em class="lxt_ic asb_l"></em></li>';
            }

            linehtml += '<p></p>'
        }
        queshtml += '</ul>';
        answhtml += '</ul>';

        var quesDom = $(queshtml);
        var answDom = $(answhtml);
        $('#card_list_line').html(linehtml);
        $('#card_question_ul').html(quesDom);
        $('#card_answer_ul').html(answDom);
        _self.init();

        // 禁用enter换行
        $('textarea').on('keydown', function (e) {
            var key = e.which;
            if (key == 13) {
                e.preventDefault();
            }
        });

        // 左侧逻辑
        quesDom.find('.lxt_edit_img').click(function () {
            var index = $(this).parents('li').index();
            _self.selectImg().done(function (imgUrl) {
                if (imgUrl != null) {
                    _self.MatchCardQues[index].type = 'img';
                    _self.MatchCardQues[index].value = imgUrl;
                    _self.showEditCardList();
                }
            });
        });
        quesDom.find('.lxt_edit_text').click(function () {
            var index = $(this).parents('li').index();
            $(this).parents('li').html('<textarea class="lxt_edit_input" placeholder="请输入文字"></textarea><em class="lxt_ic asb_r"></em>');
            //进入textarea焦点
            $('#card_question_ul ul li:eq(' + index + ')').find('textarea').focus();
            // 禁用enter换行
            $('textarea').on('keydown', function (e) {
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                }
            });
        });
        quesDom.find('.graph_list_close').click(function(){
            var index = $(this).parents('li').index();
            _self.MatchCardQues[index].type = '';
            _self.MatchCardQues[index].value = '';
            _self.showEditCardList();
        });

        // 右侧逻辑
        answDom.find('.lxt_edit_img').click(function () {
            var index = $(this).parents('li').index();
            _self.selectImg().done(function (imgUrl) {
                if (imgUrl != null) {
                    _self.MatchCardAnsw[index].type = 'img';
                    _self.MatchCardAnsw[index].value = imgUrl;
                    _self.showEditCardList();
                }
            });
        });
        answDom.find('.lxt_edit_text').click(function () {
            var index = $(this).parents('li').index();
            $(this).parents('li').html('<textarea class="lxt_edit_input" placeholder="请输入文字"></textarea><em class="lxt_ic asb_l"></em>');
            //进入textarea焦点
            $('#card_answer_ul ul li:eq(' + index + ')').find('textarea').focus();
            // 禁用enter换行
            $('textarea').on('keydown', function (e) {
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                }
            });
        });
        answDom.find('.graph_list_close').click(function () {
            var index = $(this).parents('li').index();
            _self.MatchCardAnsw[index].type = '';
            _self.MatchCardAnsw[index].value = '';
            _self.showEditCardList();
        });
    }


    /**
     * 预览列表
     * @param flag 是否打乱排序（true：是、false:否）
     */
    this.previewCardList = function (flag) {
        _self.isRandom = flag;

        _self.Mcq = [];
        _self.Mca = [];
        // 打乱排序
        for (var i = 0; i < _cardNum; i++) {
            _self.Mcq.push(_self.MatchCardQues[i]);
            _self.Mca.push(_self.MatchCardAnsw[i]);
        }

        if (flag) {
            _self.Mcq.sort(function () {
                return 0.5 - Math.random(1)
            });
        }
        _self.Mca.sort(function () {
            return 0.5 - Math.random(1)
        });


        var queshtml = '<ul class="lxt_temp_ul2 clearfix">';
        var answhtml = '<ul class="lxt_temp_ul2 clearfix">';
        var linehtml = '';
        for (var i = 0; i < _cardNum; i++) {
            // 左侧列表
            if (_self.Mcq[i].type === 'img') {
                queshtml += '<li class="lxt_edit"><img src="' + _self.Mcq[i].value + '"><em class="lxt_ic asb_r"></em></li>';
            } else {
                queshtml += '<li class="lxt_edit"><div><span>' + _self.Mcq[i].value + '</span></div><em class="lxt_ic asb_r"></em></li>';
            }
            // 右侧列表
            if (_self.Mca[i].type === 'img') {
                answhtml += '<li class="lxt_edit"><img src="' + _self.Mca[i].value + '"><em class="lxt_ic asb_l"></em></li>';
            } else {
                answhtml += '<li class="lxt_edit"><div><span>' + _self.Mca[i].value + '</span></div><em class="lxt_ic asb_l"></em></li>';
            }

        }
        queshtml += '</ul>';
        answhtml += '</ul>';
        $('#pre_card_title').html($(".match_title").val());
        $('#card_question_ul_pre').html(queshtml);
        $('#card_answer_ul_pre').html(answhtml);
    }

    /**
     * 创建连线题数组
     */
    this.createMatchCardArray = function () {
        var matchCardQuesTmp = [];
        var matchCardAnswTmp = [];

        for (var i = 0; i < _cardNum; i++) {
            if (_self.MatchCardQues.length > 0) {
                if (i >= _self.MatchCardQues.length) {
                    var matchCard = new MatchCardItem();
                    _maxId++;
                    matchCard.id = 'q' + _maxId;
                    matchCard.type = '';
                    matchCard.value = '';
                    matchCardQuesTmp.push(matchCard);
                    var matchCard = new MatchCardItem();
                    matchCard.id = 'a' + _maxId;
                    matchCard.type = '';
                    matchCard.value = '';
                    matchCardAnswTmp.push(matchCard)
                } else {
                    matchCardQuesTmp.push(_self.MatchCardQues[i]);
                    matchCardAnswTmp.push(_self.MatchCardAnsw[i]);
                }
            } else {
                var matchCard = new MatchCardItem();
                _maxId++;
                matchCard.id = 'q' + _maxId;
                matchCard.type = '';
                matchCard.value = '';
                matchCardQuesTmp.push(matchCard);
                var matchCard = new MatchCardItem();
                matchCard.id = 'a' + _maxId;
                matchCard.type = '';
                matchCard.value = '';
                matchCardAnswTmp.push(matchCard)
            }
        }
        _self.MatchCardAnsw = matchCardAnswTmp;
        _self.MatchCardQues = matchCardQuesTmp;
    }

    /**
     * 选择图片
     * @return filePath 图片路径
     */
    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.getMatchCardInfo = function (callback) {
        _self.getThumbImgCanvasData().done(function (thumbData) {

            var matchCardItems = {'question': _self.Mcq, 'answer': _self.Mca};

            var matchCardInfo = {'maxid': _maxId,'israndom': _self.isRandom, 'cardtype': 'matchcard', "thumbnail": 'thumbnail.jpg', "style": "horizon", "title": $(".match_title").val(), 'items': matchCardItems};
            if (callback) {
                callback(matchCardInfo, thumbData);
            }
        });
    }

    /**
     * 判断是否完成编辑
     * @returns {boolean}
     */
    this.isAllComplete = function () {
        var flag = true;
        for (var i = 0; i < _cardNum; i++) {
            if (_self.MatchCardQues[i].value === '' || _self.MatchCardAnsw[i].value === '') {
                flag = false;
                break;
            }
        }
        return flag;
    }

    /**
     * 选择数量页面
     */
    this.showSelectNum = function () {
        $("#edit_card").hide();
        $("#sel_cardnum").show();
        $("#preview_card").hide();
    }
    /**
     * 编辑内容页面
     */
    this.showEditCard = function () {
        $("#edit_card").show();
        $("#sel_cardnum").hide();
        $("#preview_card").hide();
    }

    /**
     * 预览页面
     */
    this.showPreviewCard = function () {
        $("#edit_card").hide();
        $("#sel_cardnum").hide();
        $("#preview_card").show();
    }

    /**
     * 重置卡片数组
     * @param cmd
     */
    this.setCmdText = function (cmd) {
        _self.MatchCardQues = cmd.items.question;
        _self.MatchCardAnsw = _self.sortMatchCardQuesAndAnsw(cmd.items.question, cmd.items.answer);

        _cardNum = cmd.items.question.length;
        _maxId = cmd.maxid;
        $("#list_num").val(_cardNum);
        $('.match_title').val(cmd.title);
    }

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

    /**
     * 匹配连线题左右答案顺序
     * @param quesArr 问题数组
     * @param answArr 答案数组
     */
    this.sortMatchCardQuesAndAnsw = function (quesArr, answArr) {
        tmpArr = [];
        for (var i = 0; i < quesArr.length; i++) {
            var qid = quesArr[i].id.substr(1, 1);
            for (var j = 0; j < answArr.length; j++) {
                var aid = answArr[j].id.substr(1, 1);
                if (qid === aid) {
                    tmpArr.push(answArr[j]);
                    break;
                }
            }
        }
        return tmpArr;
    }

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