/**
 * Created by feiqian on 2014/7/16.
 */

define(function (require, exports, module) {
    var AppContext = require('../../../../../share/assert/js/appcontext').AppContext;
    var commands = require('../../../../../editor/assert/js/utils/commands').commands;
    var WidgetType = require('../../../../../share/assert/js/widgettype.js').Types;

    var Events = window.require('events');
    var Util = window.require('util');
    var ExerciseItem = require('./exerciseItem.js');

    /**
     * 测验卡片类型
     * @type {{CHOICE1: string, CHOICE2: string, CHOICE3: string}}
     */
    var ExerciseType = {
        CHOICE1: "1",
        CHOICE2: "2",
        CHOICE3: "3"
    };

    function ExerciseMgr() {
        this._items = [];
        this._cache = null;
        this._currExerciseIndex = 0;
        this._currExerciseType = null;
        this._currExerciseItem = null;
        this._currAnswersNum = 4;
        this._isCurExample = false;
    }

    Util.inherits(ExerciseMgr, Events.EventEmitter);


    ExerciseMgr.prototype.init = function (data, isExample, isUpdate) {
        //console.log(JSON.stringify(data));
        var defer = $.Deferred();
        if (data) {
            var _self = this;
            if (isExample) {
                var item;
                var value = data[0];
                item = new ExerciseItem(value.type, value.subject, value.title, value.options);
                item.setThumbNail(value.thumbNail);
                item.setAnswer(value.answer);
                if (item.type === _self._currExerciseItem.type
                    && item.title === _self._currExerciseItem.title
                    && item.answer[0] === _self._currExerciseItem.answer[0]) {
                    //如果当前页是样例，则不响应
                } else {
                    _self._items.push(item);
                    _self._currExerciseItem = item;
                    _self._currExerciseType = _self._currExerciseItem.type;
                    _self._currAnswersNum = _self._currExerciseItem.options.length;
                }
                //把导入样例按钮灰显
                _self._isCurExample = true;
                $("#btnExerciseExample").addClass("pop_btn_disable");
                defer.resolve();
            } else {
                this.showPanel(null, isUpdate).done(function () {
                    $.each(data, function (i, value) {
                        var item = new ExerciseItem(value.type, value.subject, value.title, value.options);
                        item.setThumbNail(value.thumbNail);
                        item.setAnswer(value.answer);
                        _self._items.push(item);
                    });

                    _self._currExerciseItem = _self._items[0];
                    _self._currExerciseType = _self._currExerciseItem.type;
                    _self._currAnswersNum = _self._currExerciseItem.options.length;
                    //var top=(window.innerHeight-360)/2;
                    //$("#exerciseTmpl").css("paddingTop",top);

                    defer.resolve();
                });
            }
        }
        else defer.resolve();
        return defer.promise();
    };

    /**
     * 获取测验模版
     * @returns {*}
     * @private
     */
    ExerciseMgr.prototype._getTemplate = function () {
        var defer = $.Deferred();
        var container;
        var baseUrl = AppContext.joinPath(AppContext.getBinPath(), "editor/assert/js/widget/exercise/template");

        if (!this._currExerciseType) {
            baseUrl = AppContext.joinPath(baseUrl, "main.html");
            container = document.body;
        }
        else {
            baseUrl = AppContext.joinPath(baseUrl, "exercise" + this._currExerciseType + ".html");
            container = this._cache.btn.container;
        }

        var _self = this;
        commands.template[!this._currExerciseType ? 'append' : 'display'](container, baseUrl, this._currExerciseItem).done(function (ret) {
            if (ret) {
                if (!_self._currExerciseType) {
                    ret.modal({show: true, backdrop: "static", keyboard: false});
                    var modalBackDivs = $('body').find(".modal-backdrop");
                    for(var i=0;i<modalBackDivs.length-1;i++){
                        $(modalBackDivs[i]).remove();
                    }
                }
                defer.resolve(ret);
            }
        });

        return defer.promise();
    };

    /**
     * 根据当前测验类型展现不同的panel
     * @param {object=} item
     * @param {boolean} isUpdate
     * @returns {*}
     */
    ExerciseMgr.prototype.showPanel = function (item, isUpdate) {
        var _self = this;
        var defer = $.Deferred();

        if (item) {
            if (item == this._currExerciseItem && this._currAnswersNum == item.options.length) {
                defer.resolve();
                return defer.promise();
            }
            this._currExerciseItem = item;
            this._currExerciseType = item.type;
            this._currAnswersNum = item.options.length;
        }

        if (!this._currExerciseItem) {
            _self._currExerciseItem = new ExerciseItem();
            _self._currExerciseItem.setOptionsNum(_self._currAnswersNum);
            _self._currExerciseItem.setType(_self._currExerciseType);
        }
        console.log(_self._items.length);
        this._getTemplate().done(function (ret) {
                if (ret) {

                    if (!_self._cache) {

                        var temp = ret.find(".test_temp");
                        temp.css({
                            position: "absolute",
                            left: ($(window).width() - temp.outerWidth()) / 2,
                            //top: ($(window).height() - 438) / 2 + $(document).scrollTop()
                            marginTop: "30px"
                        });

//                        var top=(window.innerHeight-300)/2;
//                        $("#exerciseTmpl").css("paddingTop",top);

                        _self._cache = {
                            content: ret,
                            btn: {
                                container: ret.find("#test_temp_container"),
                                btnClose: ret.find(".w_func_close"),
                                btnComplete: ret.find("#test_temp_btn_complete"),
                                btnAddItem: ret.find("#test_temp_btn_addItem"),
                                btnDeleteItem: ret.find("#test_temp_btn_deleteItem"),
                                btnSelectType: ret.find(".test_selectType"),
                                btnAnswerNum: ret.find("#test_temp_btn_answerNum"),
                                btnAnswerPop: ret.find('.check_count_pop'),
                                bottom: ret.find("#test_temp_bottom")
                            }
                        };
                        //_self._cache.btn.bottom.hide();
                        _self._cache.btn.container.css("height", "308px");
                        _self._cache.btn.bottom.children().hide();
                        //$("#btnExerciseExample").show();
                        _self._bindCommands(true);
                    }
                    else {
                        _self._cache.btn = $.extend(_self._cache.btn, {
                            btnNextType: _self._cache.content.find("#test_temp_btn_nextType"),
                            btnPreviousType: _self._cache.content.find("#test_temp_btn_previousType"),
                            btnAddImage: _self._cache.content.find(".add_img"),
                            exerciseAnswer: _self._cache.content.find('.exercise_answer'),
                            btnSetAnswer: _self._cache.content.find('.check_btn_editor'),
                            exerciseAnswerContainer: _self._cache.content.find('.exercise_answer_container')
                        });

                        _self._closePopElement();
                        _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.btnNextType[ _self._items.length <= 0 || ( _self._items.length == 1 && _self._currExerciseItem == _self._items[0]) ? 'hide' : 'show']();
                        _self._cache.btn.btnPreviousType[ _self._items.length <= 0 || ( _self._items.length == 1 && _self._currExerciseItem == _self._items[0]) ? '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");

                        _self._cache.btn.btnAnswerNum[0].innerHTML = '<span class="pop_btn_s2">选题数量<em>' + _self._currAnswersNum + '</em><i></i></span>';
                        _self._cache.btn.btnAnswerPop.find(".current").removeClass("current");
                        _self._cache.btn.btnAnswerPop.find("li")[_self._currAnswersNum - 2].className = 'current';
                        $.each(_self._currExerciseItem.answer, function (i, value) {
                            value = parseInt(value, 36);
                            if (value >= 10) value -= 10;
                            if (!isNaN(value) && value >= 0 && value < _self._cache.btn.btnSetAnswer.length) _self._cache.btn.btnSetAnswer[value].className += " checked";
                        });

                        //_self._cache.btn.bottom.show();
                        _self._cache.btn.container.css("height", "478");
                        _self._cache.btn.bottom.children().show();

                        $("#btnExerciseExample").show();
                        //如果还没有导入样例，则把导入样例按钮启用
                        if (!_self._isCurExample) {
                            $("#btnExerciseExample").removeClass("pop_btn_disable");
                        }
                        if (isUpdate) {
                            $("#btnExerciseExample").addClass("pop_btn_disable");
                        }
                        //设置选项居中
                        /*
                         setTimeout(function(){
                         var height  =  _self._cache.btn.exerciseAnswerContainer.height();
                         if(height) _self._cache.btn.exerciseAnswerContainer.css("paddingTop",(_self._cache.btn.exerciseAnswerContainer.parent().height() - height)/2);
                         else setTimeout(arguments.callee,50);
                         },50);
                         console.log(_self._cache.btn.exerciseAnswerContainer.height())
                         */
                    }
                    defer.resolve(ret);
                }
            }
        );

        return defer.promise();
    };


    ExerciseMgr.prototype._bindCommands = function (index) {
        var _self = this;
        /**
         * 关闭按钮
         * 或使用modal('hide')关闭弹框时的回调
         */
        _self._cache.content.on('hidden.bs.modal', function (e) {
            Global.isEditing = false;
        });

        if (index) {
            _self._cache.btn.btnClose.on('click', function () {
                _self.closePanel();
                event.stopPropagation();
            });

            _self._cache.btn.btnComplete.on('click', function () {
                var errMsg = _self._saveCurrExerciseItem();
                var index = null;
                if (!errMsg) {
                    index = null;
                    $.each(_self._items, function (i, value) {
                        errMsg = value.getCompleteInfo();
                        if (errMsg) {
                            index = i;
                            return false;
                        }
                    });
                }
                else index = _self._currExerciseIndex;


                if (index != null) {
                    commands.showSelectorPop(errMsg, null, null, this, [
                        {
                            label: '确定',
                            cssClass: 'btn-primary',
                            action: function () {
                                commands.hidePop();
                            }}
                    ]
                    );
                    _self._currExerciseIndex = index;
                    _self.showPanel(_self._items[index]);
                }
                else {
                    _self.once('save', function () {
                        _self.closePanel();
                    });
                    _self.save();
                }
                event.stopPropagation();
            });

            _self._cache.btn.btnDeleteItem.on('click', function () {
                _self._items = _self._items.filter(function (value) {
                    return value != _self._currExerciseItem;
                });
                //当最后一道题时，清空最后一道题，需要设置当前状态为未导入样例
                if (_self._items.length === 0) {
                    _self._isCurExample = false;
                }
                _self._currExerciseIndex = (_self._currExerciseIndex - 1 + _self._items.length) % (_self._items.length ? _self._items.length : 1 );
                _self._currExerciseItem = null;
                _self.showPanel(_self._items[_self._currExerciseIndex]);
                event.stopPropagation();
            });

            _self._cache.btn.btnSelectType.on('click', function () {
                var target = event.target || event.srcElement;
                if (target.tagName == 'IMG') {
                    var type = target.getAttribute('type');
                    if (type) {
                        var currentSubject;
                        if (_self._currExerciseType) {
                            _self._saveCurrExerciseItem();
                            _self._currExerciseIndex = _self._items.length;
                            //下面这个是为了以后有可能做成当前页后面插入新的一页
                            //_self._currExerciseIndex = _self._currExerciseIndex+1;
                            currentSubject = _self._currExerciseItem.subject;
                        }
                        _self._currExerciseType = type;

                        _self._currExerciseItem = new ExerciseItem();
                        _self._currExerciseItem.setOptionsNum(_self._currAnswersNum);
                        _self._currExerciseItem.setType(_self._currExerciseType);
                        _self._currExerciseItem.setSubject(currentSubject);
                        //新建题目时，需要设置当前状态为未导入样例
                        _self._isCurExample = false;
                        _self.showPanel();
                    }
                }

                event.stopPropagation();
            });

            //导入样例按钮点击事件
            $("#btnExerciseExample").on('click', function () {
                var items;
                if (_self._currExerciseItem.type === ExerciseType.CHOICE1) {
                    items = [
                        {"type": "1", "title": "1、秦王嬴政在全国范围内确立了中央集权的政治制度。中央集权指", "options": [
                            {"type": "text", "value": "全国有统一的货币、度量衡"},
                            {"type": "text", "value": "全国有通行的统一文字"},
                            {"type": "text", "value": "以皇权至高无上为最基本的原则"},
                            {"type": "text", "value": "中央机构对地方机构实行直接有效的行政管理"}
                        ], "answer": [3], "subject": _self._cache.btn.container.find('.exercise_subject').val()}
                    ];
                }
                if (_self._currExerciseItem.type === ExerciseType.CHOICE2) {
                    items = [
                        {"type": "2", "title": "2、下图为澳门特别行政区区旗的是", "options": [
                            {"type": "img", "value": AppContext.getExerciseExamplePath() + "/media/Exercise1/TKJL8.PNG"},
                            {"type": "img", "value": AppContext.getExerciseExamplePath() + "/media/Exercise1/Pzo1N.PNG"},
                            {"type": "img", "value": AppContext.getExerciseExamplePath() + "/media/Exercise1/4zkRy.PNG"},
                            {"type": "img", "value": AppContext.getExerciseExamplePath() + "/media/Exercise1/UvoA3.PNG"}
                        ], "answer": [3], "subject": _self._cache.btn.container.find('.exercise_subject').val()}
                    ];
                }
                if (_self._currExerciseItem.type === ExerciseType.CHOICE3) {
                    items = [
                        {"type": "3", "title": "3、右图是鲁迅哪部作品的人物", "options": [
                            {"type": "text", "value": "呐喊"},
                            {"type": "text", "value": "朝花夕拾"},
                            {"type": "text", "value": "阿Q正传"},
                            {"type": "text", "value": "彷徨"}
                        ], "answer": [2], "thumbNail": AppContext.getExerciseExamplePath() + "/media/Exercise1/aQwiy.PNG", "subject": _self._cache.btn.container.find('.exercise_subject').val()}
                    ];
                }
                _self.init(items, true).done(function () {
                    _self.showPanel();
                });
            });

            _self._cache.btn.btnAddItem.on('click', function () {
                _self._cache.btn.btnSelectType.toggle();
                event.stopPropagation();
            });

            _self._cache.btn.btnAnswerNum.on('click', function () {
                _self._cache.btn.btnAnswerPop.toggle();
                event.stopPropagation();
            });

            _self._cache.btn.btnAnswerPop.on('click', function () {
                var target = event.target || event.srcElement;
                if (target.tagName == "LI") {
                    var num = parseInt(target.innerHTML);
                    if (_self._currAnswersNum != num) {
                        _self._cache.btn.btnAnswerNum[0].innerHTML = '<span class="pop_btn_s2">选题数量<em>' + num + '</em><i></i></span>';
                        _self._cache.btn.btnAnswerPop.find(".current").removeClass("current");
                        target.className = 'current';

                        _self._saveCurrExerciseItem(true);
                        _self._currExerciseItem.setOptionsNum(num);
                        _self.showPanel(_self._currExerciseItem);
                    }
                }
                event.stopPropagation();
            });

            _self._cache.btn.container.on('click', function () {
                if (_self._currExerciseType) {
                    _self._closePopElement();
                }
                event.stopPropagation();
            });
        }
        else {
            _self._cache.btn.btnNextType.on('click', function () {
                console.log(_self._items);
                var item = _self._items[_self._currExerciseIndex + 1];
                if (item) {
                    _self._saveCurrExerciseItem();
                    ++_self._currExerciseIndex;
                    _self.showPanel(item).done(function () {
                        var container = _self._cache.btn.container.find(".exercise_options");
                        container.css("left", container.outerWidth()).animate({left: "0px"});
                        console.log(_self._items);
                    });
                }
                event.stopPropagation();
            });

            _self._cache.btn.btnPreviousType.on('click', function () {
                console.log(_self._items);
                var item = _self._items[_self._currExerciseIndex - 1];
                if (item) {
                    _self._saveCurrExerciseItem();
                    --_self._currExerciseIndex;
                    _self.showPanel(item).done(function () {
                        var container = _self._cache.btn.container.find(".exercise_options");
                        container.css("left", -container.outerWidth()).animate({left: "0px"});
                        console.log(_self._items);
                    });
                }
                event.stopPropagation();
            });

            _self._cache.btn.btnAddImage.on('click', function () {
                _addImg($(this).children()[0]);
                event.stopPropagation();
            });
            function _addImg(imgEle) {
                var _this = imgEle;
                var options = {multiple: false, accept: "image/jpg, image/jpeg, image/bmp, image/gif, image/png"};
                commands.openFileDialog(options).done(function (filePath) {
                    _this.src = filePath;

                    _this.onerror = function () {
                        _this.onerror = null;
                        _this.src = 'editor/assert/images/btn_gallery_add.jpg';
                        commands.showSelectorPop(commands.getErrorMsg(2021), null, null, this, [
                            {
                                label: '确定',
                                cssClass: 'btn-primary',
                                action: function () {
                                    commands.hidePop();
                                }}
                        ]
                        );
                    };
                });
                event.stopPropagation();
            }

            //_self._cache.btn.btnAddImage.one('load', function () {
            //    $(this).css('background', 'none');
            //    event.stopPropagation();
            //});

            _self._cache.btn.btnSetAnswer.on('click', function () {
                if (this.className.indexOf('checked') == -1) this.className += " checked";
                else this.className = this.className.replace('checked', '');
                event.stopPropagation();
            });

            //给测验标题栏设定65个字符限制
            _self._cache.btn.container.find('.exercise_subject').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);
                }
                _self._currExerciseItem.setSubject(this.value);
            });

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

        }
    };


    ExerciseMgr.prototype.closePanel = function () {
        this._cache.content.modal && this._cache.content.modal('hide');
        var _self = this;
        setTimeout(function () {
            _self._cache.content.remove();
            $("body").find(".modal-backdrop").remove();
            _self._cache = null;
        }, 500);
    };


    ExerciseMgr.prototype.toJSON = function () {
        var exerciseInfo = {"cardtype": WidgetType.Exercise.toLocaleLowerCase(), "thumbnail": 'thumbnail.png', "items": this._items};
        return exerciseInfo;
    };

    ExerciseMgr.prototype._closePopElement = function () {
        this._cache.btn.btnSelectType.hide();
        this._cache.btn.btnAnswerPop.hide();
    };

    /**
     * 保存当前类型的测验卡片
     * @param {boolean=} bNotWrite
     * @returns {*}
     * @private
     */
    ExerciseMgr.prototype._saveCurrExerciseItem = function (bNotWrite) {
        var _self = this;
        var item = this._currExerciseItem;
        if (!this._currExerciseType || !item || !item.type) return;

        if (!bNotWrite) {
            if ($.inArray(item, this._items) == -1) {
                //如果当前页是空白题，则不需要push
                if (!_self._isItemEmpty(item)) {
                    this._items.push(item);
                }
            }
            ;
        }

        var container = this._cache.btn.container;
        var currSubject = container.find('.exercise_subject').val();
        $.each(this._items, function (i, ele) {
            ele.setSubject(currSubject);
        });
        item.setTitle(container.find('.exercise_title').val());

        switch (item.type) {
            case ExerciseType.CHOICE3:
                item.setThumbNail(this._cache.btn.btnAddImage.children().attr('src'));
            case ExerciseType.CHOICE1:
                item.setOptions(this._cache.btn.exerciseAnswer.map(function () {
                    return this.value;
                }).get(), "text");
                break;
            case ExerciseType.CHOICE2:
                item.setOptions(this._cache.btn.btnAddImage.children().map(function () {
                    return this.getAttribute('src');
                }).get(), "img");
                break;
            default :
                return;
        }

        item.setAnswer(this._cache.btn.btnSetAnswer.map(function () {
            if (this.className.indexOf('checked') != -1) {
                var value = this.nextElementSibling.innerHTML.substr(0, 1);
                value = parseInt(value, 36);
                if (value >= 10) value -= 10;
                if (isNaN(value))  return parseInt(this.getAttribute('index'));
                else return value;
            }
        }).get());

        var getCompleteInfo = item.getCompleteInfo();
        return getCompleteInfo;
    };

    ExerciseMgr.prototype._isItemEmpty = function (item) {
        var isItemEmpty = true;
        if (item.title || item.subject || item.answer.length > 0) {
            isItemEmpty = false;
        }
        for (var i = 0; i < item.options.length; i++) {
            if (item.options[i].value) {
                isItemEmpty = false;
            }
        }
        return isItemEmpty;
    }

    ExerciseMgr.prototype.save = function () {
        var _self = this;
        _self.getThumbImgCanvasData().done(function (thumbData) {
            _self.emit('save', JSON.parse(JSON.stringify(_self)), thumbData);
        });
    };

    /**
     * 截取当前卡片的缩略图canvas
     */
    ExerciseMgr.prototype.getThumbImgCanvasData = function () {
        var def = $.Deferred();
        this._closePopElement();
        var _self = this;
        this.showPanel(this._items[0]).done(function () {

            _self._cache.btn.container.find(".exercise_subject").parent('div').css({
                'height': '43px',
                'width': '598px',
                'margin-left': '-15px',
                'background': '-webkit-linear-gradient(top, #f9f9f9, #e7e7e7)',
                'border-bottom': '1px solid #a6a7a6'});
            _self._cache.btn.container.find(".exercise_subject").css({
                'border': '0',
                'width': '580px',
                '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'
            });
            _self._cache.btn.container.find(".add_answer").css({"border": "0px", "border-radius": "0px", "box-shadow": "none"});

            html2canvas(_self._cache.btn.container[0], {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    _self._cache.btn.container.find(".add_answer").css({"border": "1px solid #bec3c7", "border-radius": "3px", "box-shadow": "inset 0 0 3px #ccc"});
                    def.resolve(data);
                }
            });
        });
        return def.promise();
    };

    //添加template_number方法
    commands.template.helper('template_number', function (data) {
        return new Number(data);
    });

    module.exports = ExerciseMgr;
});