/**
 * Created with JetBrains WebStorm.
 * User: haozeswin7,dfwang
 * Date: 14-6-24
 * Time: 上午8:44
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {
        var Slide = require('../../../share/assert/js/slide').Slide;
        var IO = require('share/assert/js/ioutil_desktop').IOUtil;
        var commands = require('editor/assert/js/utils/commands').commands;
        var AppContext = require('share/assert/js/appcontext').AppContext;

        Slide.prototype.getActiveObject = function () {
            return this.activeObject || this._canvas.getActiveObject() || this._canvas.getActiveGroup();
        };
        Slide.prototype._initEditingMode = function (callback) {

            var _self = this;
            var _selGroup = false;
            //先停用
            this._canvas.on('createThumb', function (e) {
                commands.showThumbImg(_self._canvas);
            });
            /**
             * 选择对象时
             */
            this._canvas.on('object:selected', function (evt) {
                Global.curSelStatus = "widget";
                commands.resetDeleteBtn(true);
                if(!Global.CurrentSlide.c._canvas.getActiveObject()){
                    commands.resetExportBtn(false);
                } else
                if(Global.CurrentSlide.c._canvas.getActiveObject().type.toLocaleLowerCase() === 'spot'){
                    commands.resetExportBtn(false);
                } else {
                    commands.resetExportBtn(true);
                }

                if (evt.target._objects) {
                    //var _gobj = _self.getActiveGroup();

                    /*if(!_selGroup){
                        _selGroup = true;
                        commands.saveCtrlPath('object');
                    }*/
//                    console.log(Global.CurrentSlide.c._canvas.toDatalessJSON())
                    commands.usePropertyCtrlArea(null, true);
//                    Global.CurrentSlide.c._canvas.getActiveGroup().destroy();
//                    Global.CurrentSlide.c._canvas.fire('selection:cleared', { e: evt })
                    //commands.saveCtrlPath('object');
                    /*setTimeout(function(){

                    },2000)*/
                    return;
                }else
                {
                    //commands.saveCtrlPath('object');
                }
                var _aobj = _self.getActiveObject();
                if (_aobj && evt.target != _aobj) {
                    _aobj.hideEditButton();
                }
                var _t = evt.target;
                /*try{
                 _t = eval('new '+commands.objectToClass(evt.target.ftype || evt.target.type)+'()');
                 }catch (error)
                 {
                 throw('没有找到对象');
                 }*/

                Global.CurrentSlide.c.activeObject = _t;
                _t.showEditButton(Global.CurrentSlide.c);
            });
            /**
             * 对象被修改时需要更新缩略图
             */
            this._canvas.on('object:modified', function (evt) {
                Global.curSelStatus = "widget";
                commands.resetDeleteBtn(true);
                Global.isVariety = true;
                commands.saveCtrlPath('modified');
                commands.showThumbImg(Global.CurrentSlide.c._canvas);
            });

            this._canvas.on('object:added', function (evt) {
                if (!Global.AppState.init.value){
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                    Global.isAdded = true;
                }
                //Global.isVariety = true;
            });
            this._canvas.on('object:removed', function (evt) {
                Global.isVariety = true;
                setTimeout(function () {
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                }, 100)
            });
            this._canvas.on('text:changed',function(evt){
                var _textarea = evt.target.hiddenTextarea;
                var _that = evt.target;
                var _soffw = 0
                var _soffh = 0;
				Global.isVariety = true;
                if(_textarea.parentNode.tagName === 'BODY')
                {
                    var _off = this.upperCanvasEl.getBoundingClientRect();
                    _soffw = (_that.left)*DEFAULT_STAGE.scale + _off.left;
                    _soffh = (_that.height*_that.scaleX+_that.top)*DEFAULT_STAGE.scale + _off.top;
                }else
                {
                    _soffw = _that.left;
                    _soffh = (_that.height*_that.scaleY)+_that.top;
                }

                $(_textarea).css('top',_soffh)
                $(_textarea).css('left',_soffw)
                $(_textarea).css('width',1)
                $(_textarea).css('opacity',0.01)
            })

            /* this._canvas.on('object:selected',function(evt){
             if(evt.target._objects && evt.target._objects.length>1) return;

             })*/
            /**
             * 取消选择
             */
            this._canvas.on('selection:cleared', function (evt) {
                //commands.showThumbImg(Global.CurrentSlide.c._canvas);
                _selGroup = false;
                commands.closeToolsPop();
                var _aobj = _self.getActiveObject();
                if (!_aobj) {
                    commands.usePropertyCtrlArea(null, null);
                    return;
                }
                if (evt.target && evt.target != _aobj) {
                    _aobj.hideEditorBtn ? _aobj.hideEditorBtn() : _aobj.hideProperty();
                } else {
                    _aobj.hideEditButton();
                }
            });
            this._canvas.on('canvas:cleared',function(evt){
                //$(this.wrapperEl.parentNode).remove();
                //delete  this;
            })

            //右键点击fabric canvas
            this._canvas.on('mouse:up', function (evt) {
                if (evt.e.which === 3) {
                    if (evt.target) {   //点击的是widget
//                        var activeObj = _self._canvas.getActiveObject();
                        var activeGroup = _self._canvas.getActiveGroup();
                        if(activeGroup){    //多选
                            Global.curSelStatus = "widget";
                            commands.resetDeleteBtn(true);
//                            _self._canvas.setActiveGroup(activeGroup);
                            $("#rightBtnCopy").hide();
                            $("#rightBtnCut").hide();
                            $("#rightBtnExport").hide();
                            $("#rightBtnPaste").hide();
                            $("#rightBtnDelete").show();
                        }else{
                            AppContext.rightClicked = {type: "widget", slideName: _self.Name, obj: evt.target};
//                            _self._canvas.setActiveObject(evt.target);
                            $("#rightBtnCopy").show();
                            $("#rightBtnCut").show();
                            $("#rightBtnExport").show();
                            $("#rightBtnDelete").show();
                            $("#rightBtnPaste").hide();
                            if(_self._canvas.getActiveObject().type == "Spot"){
                                $("#rightBtnExport").hide();
                            }
                        }
                        $("#contextMenu").css({left: evt.e.x, top: evt.e.y});
                        $("#contextMenu").show();
                    }else{
//                        _self._canvas.deactivateAll();
//                        _self._canvas.renderAll();
                        $("#inline-btn").remove();
                        //点击的是页面
                        if(AppContext.selectedCopyTarget){
                            $("#rightBtnPaste").show();
                            $("#rightBtnCopy").hide();
                            $("#rightBtnCut").hide();
                            $("#rightBtnExport").hide();
                            $("#rightBtnDelete").hide();
                            $("#contextMenu").css({left: evt.e.x, top: evt.e.y});
                            $("#contextMenu").show();
                        }
                    }
                }
            });

            this._canvas.on('mouse:down', function(evt){   //只有左键
                if (evt.target) {    //点击的是widget
                    Global.curSelStatus = "widget";    //重新设置状态，防止出现选中widget后再点击就不能删除的问题
                    commands.resetDeleteBtn(true);
                    if(!Global.CurrentSlide.c._canvas.getActiveObject()){
                        commands.resetExportBtn(false);
                    } else
                    if(Global.CurrentSlide.c._canvas.getActiveObject().type.toLocaleLowerCase() === 'spot'){
                        commands.resetExportBtn(false);
                    } else {
                        commands.resetExportBtn(true);
                    }
                }
                else{
                    Global.curSelStatus = null;
                    commands.resetDeleteBtn(false);
                    commands.resetExportBtn(false);
                }
            });

            this.start().done(function () {
                callback && callback();
            });
        };
        /**
         * 开始创建canvas
         */
        Slide.prototype.start = function () {
            var def = $.Deferred();
            var _that = this;
            //if (this.isFile) {
            /*if(this._canvas._objects.length>0 || this._canvas.backgroundColor!='white' || this._canvas.backgroundImage)
            {
                _that.loadFromJSON(_that.toJSON(), function (e) {
                    _that._canvas.renderAll();
                    setTimeout(function () {
//                                        commands.resetAppState();
                        Global.isVariety = Global.isVarietyType;
                        def.resolve();
                    }, 100)
                });
            }else
            {*/
                IO.exists(_that.getCurJsonPath()).done(function () {
                    if (arguments[0]) {
                        IO.readFile(_that.getCurJsonPath()).done(function () {
                            var a = {}
                            try{
                                a = JSON.parse(arguments[0]);
                            }catch (err)
                            {
                                throw  err;
                            }
                            if (a) {
                                try {
                                    _that.loadFromJSON(a, function (e) {
                                        _that._canvas.renderAll();
                                        setTimeout(function () {
//                                        commands.resetAppState();
                                            Global.isVariety = Global.isVarietyType;
                                            def.resolve();
                                        }, 100)
                                    });
                                } catch (error) {
                                    throw error;
                                }
                            }
                        })
                    } else {
                        _that.renderAll();
                        setTimeout(function () {
                            def.resolve();
                        }, 100);
                    }
                });
           // }

            return def.promise();
        }
    }
);