/**
 * Created by feiqian on 2014/7/21.
 */
define(function (require, exports, module) {

    var _cardbase = require('./cardbase');
    var _define = require('../define');
    var tplparse = require('../thirdparty/template');

    var CheckStatus = {
        UNCHECKED: "0",
        WRONG: "1",
        RIGHT: "2"
    };

    function Exercise(options) {
        this._items = [];
        this._cache = null;
        this._currExerciseIndex = 0;
        this._currExerciseType = null;
        this._currExerciseItem = null;
        this.init(options);
    }

    Exercise.prototype = new _cardbase.CardBase();
    Exercise.prototype.constructor = Exercise;


    Exercise.prototype.getCardName = function () {
        return _define.CardName.Exercise;
    };

    Exercise.prototype.init = function (options) {
        if (!options) return;
        this._items = options.items;

        $.each(this._items, function (i, item) {
            $.each(item.options, function (i, option) {
                option.optionStyle = new Number(i + 10).toString(36).toUpperCase();
            });
            item.itemIndex = i + 1;
            item.itemsLength = options.items.length;
            item.itemType = item.answer.length <= 1 ? "单选题" : "多选题";
            item.status = CheckStatus.UNCHECKED;
            item.currAnswers = [];
        });
    };

    Exercise.prototype._getTemplate = function () {
        var _self = this;
        var defer = $.Deferred();
        this.getTemplate(this._currExerciseType).done(function (tpl) {
            if (!tpl) {
                alert("模版获取错误");
                return;
            }
            var html = $(tplparse.render(tpl, _self._currExerciseItem));
            defer.resolve(html);
        });
        return defer.promise();
    };

    Exercise.prototype.showPanel = function (left, top) {
        var defer = $.Deferred();
        var _self = this;

        var defer2 = $.Deferred();
        if (!this._cache) {
            this._getTemplate().done(function (html) {
                left && html.css("left", left);
                top && html.css("top", top);
                _self._cache = {
                    content: html,
                    btn: {
                        title: html.find(".exerciseTitle"),
                        container: html.find(".ceyan_box"),
                        btnNextType: html.find(".btn_scene_next"),
                        btnPreviousType: html.find(".btn_scene_prev"),
                        btnCorrectAnswer: html.find(".btn_answer"),
                        btnResultImg: html.find(".resultImg")
                    }
                };
                _self._bindCommands(true);
                defer2.resolve();
            });
        }
        else defer2.resolve();

        if (!this._currExerciseItem || this._currExerciseItem != this._items[this._currExerciseIndex]) {
            this._currExerciseItem = this._items[this._currExerciseIndex];
            this._currExerciseType = this._currExerciseItem.type;
            _self._cache.btn.title.html(_self._currExerciseItem.subject);
        }

        defer2.promise().done(function () {
            _self._getTemplate().done(function (html) {
                _self._cache.btn.container.empty();
                _self._cache.btn.container.append(html);
                _self._cache.btn = $.extend(_self._cache.btn, {
                    btnSetAnswer: _self._cache.content.find(".check_btn"),
                    exerciseOptionsContainer: _self._cache.content.find('.excerciseContainer'),
                    exerciseAnswerContainer: _self._cache.content.find('.excerciseDetail')
                });
                _self._bindCommands(false);

//                _self._cache.btn.btnNextType[_self._currExerciseIndex >= _self._items.length-1 ? 'hide' : 'show']();
//                _self._cache.btn.btnPreviousType[_self._currExerciseIndex <= 0 ? 'hide' : 'show']();
                _self._cache.btn.title.html(_self._currExerciseItem.subject);
                _self._cache.btn.btnNextType[ _self._items.length <= 1 ? 'hide' : 'show']();
                _self._cache.btn.btnPreviousType[ _self._items.length <= 1 ? 'hide' : 'show']();

                _self._cache.btn.btnNextType[_self._currExerciseIndex >= _self._items.length - 1 ? 'addClass' : 'removeClass']("disabled");
                _self._cache.btn.btnPreviousType[_self._currExerciseIndex <= 0 ? 'addClass' : 'removeClass']("disabled");


                //设置选项居中
                if(_self._currExerciseItem.type != "3"){
                    setTimeout(function () {
                        var domHeight = _self._cache.content.height();
                        var domWidth = _self._cache.content.width();
                        var classified_box_height = domHeight - 100;
                        var outerContainerHeight = classified_box_height - 90;
                        _self._cache.btn.exerciseOptionsContainer.parent().css("height", outerContainerHeight);

                        //第二种图片题的图片高度、宽度
                        var imgHeight = Math.floor((outerContainerHeight - 40) / 3);
                        var imgWidth = Math.floor((domWidth - 380) / 2);
                        //_self._cache.btn.exerciseAnswerContainer.find(".checkBtnContainer").css({"height": imgHeight, "width": imgWidth});
                        _self._cache.btn.exerciseAnswerContainer.find(".add_img").css({"height": imgHeight, "width": imgWidth});
                        var innerHeight = _self._cache.btn.exerciseAnswerContainer.height();
                        var outerHeight = _self._cache.btn.exerciseOptionsContainer.parent().parent().height() - 85;
                        var ulMarginTop = (outerHeight - innerHeight) / 2 > 0 ? (outerHeight - innerHeight) / 2 : 0
                        console.log("ulMarginTop:: " + ulMarginTop);
                        if (innerHeight && outerHeight) {
                            var lineHeightStr = imgHeight - 20 + "px";
                            if(_self._currExerciseItem.type === "2"){
                                _self._cache.btn.exerciseAnswerContainer.css("line-height",lineHeightStr);
                            }
                            _self._cache.btn.exerciseAnswerContainer.css("margin-top",ulMarginTop);
                        } else {
                            setTimeout(arguments.callee, 0);
                        }
                    }, 0);
                }
                //_self._setAnswers();
                _self._resetAnswers();
                defer.resolve(html);
            });
        });
        return defer.promise();
    };

    Exercise.prototype._bindCommands = function (index) {
        var _self = this;

        function getCheckedAnswers() {
            var arr = [];
            $.each(_self._cache.btn.btnSetAnswer, function (i, ele) {
                if (ele.className.indexOf('checked') != -1) {
                    arr.push({
                        index: i,
                        ele: ele
                    });
                }
            });
            return arr;
        }

        if (index) {
            this._cache.btn.btnNextType.on('vclick', function () {
                if (_self._currExerciseIndex + 1 >= _self._items.length) return true;
                _self._currExerciseIndex = _self._currExerciseIndex + 1;
                _self.showPanel().done(function () {
                    _self._cache.btn.exerciseOptionsContainer.css("left", _self._cache.btn.exerciseAnswerContainer.outerWidth()).animate({left: "0px"});
                });
                event.stopPropagation();
            });

            this._cache.btn.btnPreviousType.on('vclick', function () {
                if (_self._currExerciseIndex - 1 < 0) return true;
                _self._currExerciseIndex = _self._currExerciseIndex - 1;
                _self.showPanel().done(function () {
                    _self._cache.btn.exerciseOptionsContainer.css("left", -_self._cache.btn.exerciseAnswerContainer.outerWidth()).animate({left: "0px"});
                });
                event.stopPropagation();
            });

            this._cache.btn.btnCorrectAnswer.on('vclick', function () {
                if (_self._currExerciseItem.status != CheckStatus.UNCHECKED) {
                    this.innerHTML = "核对答案";
                    _self._resetAnswers();
                    return true;
                }

                var answerRightNum = 0;
                var checkedAnswers = getCheckedAnswers();
                if (checkedAnswers.length>0) {
                    _self._currExerciseItem.currAnswers = [];
                    $.each(checkedAnswers, function (i, obj) {
                        if ($.inArray(obj.index, _self._currExerciseItem.answer) != -1) ++answerRightNum;
                        _self._currExerciseItem.currAnswers.push(obj.index);
                    });

                    var isRight = (answerRightNum == _self._currExerciseItem.answer.length && answerRightNum == checkedAnswers.length) ? true : false;
                    if (isRight) {
                        _self._cache.btn.btnResultImg[0].src = "share/assert/images/congratulation.png";
                    } else {
                        _self._cache.btn.btnResultImg[0].src = "share/assert/images/encourage.png";
                    }
                    _self._cache.btn.btnResultImg.show();
                    _self._cache.btn.btnResultImg.css("opacity", "0");
                    _self._cache.btn.btnResultImg.animate({"height": "86px", "bottom": "60px", "opacity": "1"}, 300);
                    setTimeout(function () {
                        _self._cache.btn.btnResultImg.animate({"height": "60px", "bottom": "0px", "opacity": "0"}, 300);
                        _self._cache.btn.btnResultImg.hide();
                    }, 2000);

                    $.each(_self._cache.btn.btnSetAnswer, function (i, ele) {
                        if (ele.className.indexOf('checked') != -1) {
                            if (isRight) ele.className += " checked_01";
                            else ele.className += " checked_02";
                            ele.className = ele.className.replace("checked", "");
                        }
                    });

                    //this.innerHTML=isRight?"清除答案":"再来一次";
                    this.innerHTML = "再试一次";
                    //_self._currExerciseItem.status = isRight?CheckStatus.RIGHT:CheckStatus.WRONG;
                    _self._currExerciseItem.status = CheckStatus.WRONG;
                }else{
                    _self._cache.btn.btnResultImg.show();
                    _self._cache.btn.btnResultImg[0].src = "share/assert/images/encourage.png";
                    _self._cache.btn.btnResultImg.animate({"height": "86px", "bottom": "60px", "opacity": "1"}, 300);
                    setTimeout(function () {
                        _self._cache.btn.btnResultImg.animate({"height": "60px", "bottom": "0px", "opacity": "0"}, 300);
                        _self._cache.btn.btnResultImg.hide();
                    }, 2000);
                }
                event && event.stopPropagation();
            });
        }
        else {
            this._cache.btn.btnSetAnswer.on('vclick', function () {
                if (_self._currExerciseItem.status == CheckStatus.RIGHT) {
                    return true;
                }
                if (_self._currExerciseItem.status == CheckStatus.WRONG) {
                    _self._resetAnswers();
                }

                var bSingleChoice = _self._currExerciseItem.answer.length == 1 ? true : false;
                var checkedAnswers = getCheckedAnswers();
                if (checkedAnswers.length && bSingleChoice) {
                    var _this = this;
                    $.each(checkedAnswers, function (i, obj) {
                        if (obj.ele != _this)  toggleAnswer(obj.ele, false);
                    });
                }
                toggleAnswer(this);
                event.stopPropagation();
            });
        }
    };

    function toggleAnswer(ele, index) {
        var bChecked;
        if (index != undefined) bChecked = index;
        else  bChecked = (ele.className.indexOf('checked') == -1);

        if (bChecked) ele.className += " checked";
        else ele.className = ele.className.replace(/checked/g, '');
    }

    Exercise.prototype._setAnswers = function () {
        var answers = this._currExerciseItem.currAnswers;
        if (answers.length) {
            $.each(this._cache.btn.btnSetAnswer, function (i, ele) {
                if ($.inArray(i, answers) != -1) toggleAnswer(ele, true);
            });
            this._currExerciseItem.status = CheckStatus.UNCHECKED;
            this._cache.btn.btnCorrectAnswer.triggerHandler("vclick");
        }
        else this._cache.btn.btnCorrectAnswer[0].innerHTML = "核对答案";
    };

    Exercise.prototype._resetAnswers = function () {
        var _self = this;
        $.each(_self._cache.btn.btnSetAnswer, function () {
            this.className = this.className.replace("right", "");
            this.className = this.className.replace("wrong", "");
            this.className = this.className.replace("checked", "");
        });
        _self._currExerciseItem.status = CheckStatus.UNCHECKED;
        _self._currExerciseItem.currAnswers = [];
        _self._cache.btn.btnCorrectAnswer[0].innerHTML = "核对答案";
    }

    Exercise.prototype.getContent = function () {
        return this._cache.content;
    };

    exports.Constructor = Exercise;
});