/**
 * Created with JetBrains WebStorm.
 * User: dfwang
 * Date: 14-6-14
 * Time: 上午11:23
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {
    var IO = require('share/assert/js/ioutil_desktop').IOUtil;
    var template = require('share/assert/js/template.js');
    var ziputil = window.require('ziputil/AddonZip');
    var gui = window.require('nw.gui');
    var AppContext = require('share/assert/js/appcontext').AppContext;
    var paths = require('share/assert/js/path');
    var fs = window.require('fs');
    var appUtil = require('editor/assert/js/addon/appUtil');
    var LM = require('editor/assert/js/addon/logManager').LogManager;
//    var main = require('editor/assert/js/editor.js');
    var commands = {};
    /**
     * 拷贝prototype
     * @param a
     * @param b
     * @private
     */
    commands._extend = function (a, b) {
        for (var i in b.prototype) {
            if (!a.prototype[i]) {
                a.prototype[i] = b.prototype[i]
            }
        }
    }
    /**
     * 生成随机字符串
     * @param a
     * @returns {string}
     * @private
     */
    commands.randomString = function (a) {
        var b = "";
        a = 0 < parseInt(a) ? parseInt(a) : 10;
        for (var c = 0; c < a; c++)
             var d = Math.floor(61 * Math.random()), b = b + "ABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789abcdefghiklmnopqrstuvwxyz".substring(d, d + 1);
        return b
    };

    commands.randomStringAlpha = function(a) {
        var b = "";
        a = 0 < parseInt(a) ? parseInt(a) : 10;
        for (var c = 0; c < a; c++)
             var d = Math.floor(26 * Math.random()), b = b + "abcdefghijklmnopqrstuvwxyz".substring(d, d + 1);
        return b
    };

    commands.randomStringNumber = function(a) {
        var b = "";
        a = 0 < parseInt(a) ? parseInt(a) : 10;
        for (var c = 0; c < a; c++)
             var d = Math.floor(10 * Math.random()), b = b + "0123456789".substring(d, d + 1);
        return b
    };

    commands.getAutoSaveInfo = function() {
        var tempdir = AppContext.getTmpPackPath();
        var tempfiles = [];
        var tempResult = [];

        if (fs.existsSync(tempdir)) {
            tempfiles = fs.readdirSync(tempdir);
            for(var i = 0; i < tempfiles.length;i++) {
                var curPath = tempdir + "/" + tempfiles[i];

                if (fs.statSync(curPath).isDirectory()) {
                    var asf = curPath + '/autosave.dat';
                    if(fs.existsSync(asf)) {
                        var asfObj = JSON.parse(fs.readFileSync(asf));
                        asfObj.autoSaveFile = asf;
                        tempResult.push(asfObj);
                    }
                }
            }
        }

        return tempResult;
    };

    /**
     * 生成缩略图
     * @param _can
     */
    commands.showThumbImg = function (_target, _url, _thumb) {
        var def = jQuery.Deferred();
        //Global.isEditing = true;
        var _can = _thumb || Global.CurrentSlide.t;
        var _thm = _can.getContext();
        //_thm.clearRect(0,0,_can.canvas[0].width,_can.canvas[0].height);
        var _img = new Image();
        if (_url) {
            IO.exists(_url).done(function () {
                if (arguments[0]) {
                    //_img.onload = function(){
                    _thm.attr('src', _url);//_img,0,0,_can.canvas[0].width,_can.canvas[0].height);
                    Global.CurrentSlide.c.renderAll();
                    def.resolve(true);
                    //}
                    //_img.src = _url;
                }
            })
        } else {
            if(!Global.CurrentSlide.c) return;
            try {
                IO.writeIMG(Global.CurrentSlide.c.getCurThumbPath(), _target.lowerCanvasEl.toDataURL('image/jpeg',0.4)).done(function (err) {
                    _thm.attr('src', Global.CurrentSlide.c.getCurThumbPath() + "?" + commands.randomString(10));
                    Global.CurrentSlide.c.renderAll();
                    def.resolve(true);
                })
            } catch (err) {
                def.resolve(false);
            }
        }

        return def.promise();
        //保存缩略图到json
        //Global.CurrentSlide.c.addJsonProperty({"thumb":_img.src});
    }
    /**
     * 通过stage找到缩略图
     * @param _stageId
     */
    commands.searchThumbDom = function (_stageId) {
        var _id = _stageId.split('_')[0];
        return $('#' + _id + '_Thumb_stage');
    }
    /**
     * 通过id找到stage
     * @param _stageId
     */
    commands.searchSlideById = function(_stageId){
        for (var i = 0; i < Global.SlideArray.length; i++) {
            if(Global.SlideArray[i].c.Name == _stageId)
            {
                return Global.SlideArray[i];
            }
        }
    }
    /**
     * 创建基本功能的弹出框
     * @param _str
     */
    commands.createHTPop = function (_str) {
        //var _str = ('<div id="h_t_pop">'+_str+'</div>');
        //$('#editorContainer').append(_str);
        $(_str).modal({keyboard: false})
    }
    /**
     * 根据type找到对应的类
     * @param type  插件类
     */
    commands.objectToClass = function (type) {
        if (!type) return;
        for (var i in DEFAULT_TOOLS) {
            for (var t = 0, s = DEFAULT_TOOLS[i]; t < s.length; t++) {
                if (s[t].type == type) {
                    return  s[t].name
                }
            }
        }
    }
    /**
     *  添加/删除队列中的KEYcode
     * @param code  keycode
     * @param act   操作类型 0清空 1添加 2删除
     @returns {boolean}
     */
    commands.pushKeyCode = function (code, act) {
        if (!act || code == 18) {
            Global.KeyLists = [];
            return true;
        }
        for (var i = 0; i < Global.KeyLists.length; i++) {
            if (Global.KeyLists[i] === code) {
                if (act == 2) Global.KeyLists.splice(i, 1);
                return true;
            }
        }
        if (act == 1) Global.KeyLists.push(code);
        return true;
    }
    /**
     * keyup后需要触发的事件
     * @param code
     */
    commands.fireKeyEvent = function (code) {
        var _obj = Global.CurrentSlide && Global.CurrentSlide.c.getActiveObject();
        var _objs = Global.CurrentSlide && Global.CurrentSlide.c._canvas.getActiveGroup();
//        console.log(Global.KeyLists,code,'fire');
        switch (code) {
            case 46: //del
                if(Global.curSelStatus == "widget"){
                    //EventBase.fireEvent('KeyUp',{type:'del'})
                    commands.saveCtrlPath('object');
                    if ((_obj && _obj.isEditing) || $('#modal-content').length>1) {

                    } else {
                        //commands.setAppState('init',true);
                        if (_objs) {
                            for (var i = 0; i < _objs.objects.length; i++) {
                                if (_objs.objects[i].getRelInfo()) {
    //                                IO.rmdir(AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(),_objs.objects[i].id)).done(function(){});
                                    Global.CurrentSlide.c.delRelationInfo(_objs.objects[i].getRelInfo().id);
                                }else
                                {
                                    delMediaSource(_objs.objects[i]);
                                }
                            }
                        }else if (_obj && !_objs) {
                            if(_obj.getRelInfo() && _obj.type!='Audio' && _obj.type!='Video')
                            {
    //                            IO.rmdir(AppContext.joinPath(Global.CurrentSlide.c.getCurSlidePath(),_obj.getRelInfo().src)).done(function(){});
                                Global.CurrentSlide.c.delRelationInfo(_obj.getRelInfo().id);
                            }else{
                                delMediaSource(_obj);
                            }

                        }
                        Global.CurrentSlide.c.removeObject();
                        Global.curSelStatus = null;
                        commands.resetDeleteBtn(false);
                        commands.resetExportBtn(false);
                    }
                }
                break;
            case 67: //c
                break;
            case 86: //v
                break;
            case 90:
                for(var i=0;i<Global.KeyLists.length;i++)
                {
                    if(Global.KeyLists[i]==17)
                    {
                        if((_obj && _obj.isEditing) || Global.isEditing)
                        {

                        }else
                        {
                            commands.setAppState('init',true);
                            commands.undo().done(function()
                            {

                                commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function(){
                                    commands.resetAppState();
                                    if(arguments[0]){
                                        Global.KeyLists = [];
                                    }else
                                    {
                                        Global.KeyLists = [17];
                                    }
                                });
                            });
                        }
                        break;
                    }
                }
                break;
            case 83:
                if (Global.KeyLists[0] == 17) {
                    $('#btn_save').click();
                }
                break;
            case 116:
                $('#btn_play_part1').click();
                break
        }

        function delMediaSource(_obj){
            if(_obj.rid)
            {
               var _res = Global.CurrentSlide.c.getRelationInfo(_obj.rid);
//                IO.removeFile(AppContext.joinPath(Global.CurrentSlide.c.getCurSlidePath(),_res.src)).done(function(){});
                Global.CurrentSlide.c.delRelationInfo(_obj.rid);
            }
            if(_obj.src)
            {
//                IO.removeFile(decodeURI(_obj.src).replace('file:///',''));
            }
            if(_obj._element && _obj._element.src)
            {
//                IO.removeFile(decodeURI(_obj._element.src).replace('file:///',''));
            }
            if(_obj.type === 'path-group')
            {
                _obj.remove();
            }
        }
        Global.KeyLists = [];
    };
    /**
     * 功能区域是否可用
     */
    commands.usePropertyCtrlArea = function (type, group,animate) {
        for (var i  in PROPERTY_BUTTON) {
            for (var e in PROPERTY_BUTTON[i]) {
                $('#' + PROPERTY_BUTTON[i][e]).css('display', 'none');
            }
        }
        if (type === 'textfield') {
            for (var t in PROPERTY_BUTTON.font) {
                $('#' + PROPERTY_BUTTON.font[t]).css('display', '');
            }
        }
        //显示对齐
        if (group) {
            for (var g in PROPERTY_BUTTON.global) {
                $('#' + PROPERTY_BUTTON.global[g]).css('display', '');
            }

        }
        //显示排序
        if (type) {
            for (var s in PROPERTY_BUTTON.sort) {
                $('#' + PROPERTY_BUTTON.sort[s]).css('display', '');
            }
        }
        //显示动画
        if(animate)
        {
            for (var s in PROPERTY_BUTTON.animate) {
                $('#' + PROPERTY_BUTTON.animate[s]).css('display', '');
            }
            var _obj = Global.CurrentSlide.c.getActiveObject();
            var _slide = Global.CurrentSlide.c;
            var aniInfo=_slide.getAnimationInfo(_obj.id);

            if(!aniInfo){
                $("#btnAnimationFlag")[0].innerHTML = "无动画";
            }
            if(aniInfo && aniInfo.type =="fadeIn"){
                $("#btnAnimationFlag")[0].innerHTML = "淡入";
            }
        }
    }

    /**
     * 返回当前slide在数据中的位置
     * @param slideArray
     */
    commands.getCurSlideIndex = function (_arr, _name) {

        for (var i = 0; i < _arr.length; i++) {
            if ((_name || Global.CurrentSlide.c.Name) === _arr[i]) {
                return i
            }
        }
        return 0;
    };

    /**
     * 保存widget目标目录下。zip
     * @param _fromSrc
     * @param _destSrc
     */
    commands.saveWidget = function (_fromSrc, _destSrc) {
        Global.isEditing = false;
        var defer = $.Deferred();
        commands.showPop(commands.getErrorMsg(2024));
        
        fs.readdir(_fromSrc, function (err, _fileNames) {
            IO.removeCorpseFile(_fromSrc,_fileNames).done(function(){
                ziputil.updateZipFile(_fromSrc, _destSrc, function () {
                    commands.hidePop();
                    defer.resolve(arguments[1]);
                });
            });
        });
        return defer.promise();
    };

    /**
     * 保存包到目标目录下。zip
     * @param _fromSrc
     * @param _destSrc
     */
    commands.savePackage = function (_fromSrc, _destSrc) {
        Global.isEditing = false;
        Global.isAdded = false;
        var defer = $.Deferred();

        commands.showPop(commands.getErrorMsg(2024));

        var _fileNames = [];
        for(var i=0;i<Global.SlideArray.length;i++)
        {
            _fileNames.push(Global.SlideArray[i].c.Name);
        }
        IO.removeCorpseFile(AppContext.joinPath(_fromSrc,'slides'),_fileNames).done(function(){
            commands.ratioPackageFiles().done(function(){
                ziputil.updateZipFile(_fromSrc, _destSrc, function () {
                    commands.hidePop();
                    switch (arguments[1]) {
                        case 0:
                            Global.saveToPath = _destSrc;
                            break;
                        case 1001:
                            break;
                        case 1002:
                            break;
                        case 1003:
                            break;
                        case 1100:
                            break;
                    }
                    defer.resolve(arguments[1]);
                    if (Global.AppState.close.value) {
                        commands.closeWindow();
                    }
                });
            });
        });
        return defer.promise();
    };

    /**
     * todo 未用到
     * 保存包到目标目录下。zip
     * @param _fromSrc
     * @param _destSrc
     */
    commands.savePackageWithoutPop = function (_fromSrc, _destSrc) {
        Global.isEditing = false;
        var defer = $.Deferred();
        //commands.showPop(commands.getErrorMsg(2));
        var _fileNames = [];
        for(var i=0;i<Global.SlideArray.length;i++)
        {
            _fileNames.push(Global.SlideArray[i].c.Name);
        }
        IO.removeCorpseFile(AppContext.joinPath(_fromSrc,'slides'),_fileNames).done(function(){
            commands.ratioPackageFiles().done(function(){
                ziputil.updateZipFile(_fromSrc, _destSrc, function () {
                    //commands.hidePop();
                    switch (arguments[1]) {
                        case 0:
                            Global.saveToPath = _destSrc;
                            break;
                        case 1001:
                            break;
                        case 1002:
                            break;
                        case 1003:
                            break;
                        case 1100:
                            break;
                    }
                    defer.resolve(arguments[1]);
                    if (Global.AppState.close.value) {
                        commands.closeWindow();
                    }
                });
            });
        });
        return defer.promise();
    };


    //--------------------------------------------------------/pop/
    /**
     * 显示弹出框架
     * @param _cont 信息
     */
    commands.showPop = function (_cont, _time,_close) {
        //var _s = $('.bootstrap-dialog-message')[0];
        var _timeout = 0;

        commands.PopModel(_cont,[],this,function(idx){},_close);
        if (_time) {
            _timeout = setTimeout(function () {
                commands.hidePop();
                clearTimeout(_timeout);
            }, _time)
        }
    };
    commands.hidePop = function () {
        $('#modal_content_update').remove();
        var _list = $('.modal-backdrop').length;
        $($('.modal-backdrop')[_list-1]).remove();
    };
    commands.PopModel = function(_cont,_btn,argent,_call,_close){
        var _that = this;
        var dlg = '<div id="modal_content_update" class="modal fade" tabindex="-1" role="dialog" style="padding-top: 15%;overflow:hidden;"><div class="pop_warp pop_tips">'+
                        '<div class="pop_tit">'+
                        '<span class="fl">温馨提示</span>'+
                            '<div class="w_func fr">';
                               if(!_close) dlg+='<a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal" id="pop_close_fuc"></a>'
                dlg+='</div>'+
                        '</div>'+
                        '<div class="pop_con">'+
                            '<p class="pop_tips_con">'+_cont+'</p>'+
                        '</div>'+
                        '<div class="pop_btn_box t_center" id="pop_btns_box">';
                        for(var i=0;i<_btn.length;i++)
                        {
                            dlg+='<a href="javascript:void(0)" class="pop_btn" idx="'+i+'"><span>'+_btn[i].label+'</span></a>';
                        }
                        dlg+='</div></div></div>';
        dlg = $(dlg);
        $('body').append(dlg);
        if(_btn){
            dlg.find('#pop_btns_box>a').on('click',function(e)
            {
                dlg.modal('hide');
                _call.call(argent,$(e.currentTarget).attr('idx'));
            })
        }
        if(_call)
        {
            dlg.find('#pop_close_fuc').on('click',function(){
                _call.call(argent,'close')
            })

        }
        dlg.on('hidden.bs.modal',function(e){
            dlg.remove();
        });
        dlg.modal({show: true,backdrop : "static",keyboard:false});
        return dlg;
    }
    /**
     * 显示选择弹出框架
     * @param _cont 信息
     * @_callback _cont 回调
     * @_time 计时 信息
     * @argent 来源 信息
     */
    commands.showSelectorPop = function (_cont, _callback, _time, argent, btn,_close) {
        var _timeout = 0;
        var _btn = btn,_call = _callback;
        if(_call && !_btn)
        {
            _btn = [{label:'确定',action:_call},{label:'取消',action:function(){}}];
        }
        commands.PopModel(_cont,_btn,this,function(idx){
            if(idx === 'close')
            {
                if(_call)
                {
                    _call.call(argent,'close');
                }
            }else
            {
                _btn[parseInt(idx)].action.call(argent || this,true);
            }

        },_close);
        if (_time) {
            _timeout = setTimeout(function () {
                commands.hidePop();
                clearTimeout(_timeout);
            }, _time)
        }
    };
    /**
     * 集体关闭弹出框
     */
    commands.closeToolsPop = function (id) {
        $('#edit_wrapper').off();
        var _dom = id && $('#' + id);
        if (_dom && _dom.css('display') != 'none') {

            _dom.css('display', 'none');
        } else {
            $('#bg_list_box').hide();
            $('#spot_list_box').hide();
            $('#hdmb_list_box').hide();
            $('#btn_play_list').hide();
            $('#path_list_box').hide();
            $('#openColor_div').hide();
            _dom && $('#' + id).show();
            if (id) {
                setTimeout(function () {
                    $('#edit_wrapper').on('click', function (e) {
                        if ($(e.target).closest('#bg_list_box')[0]) return;
                        $('#edit_wrapper').off();
                        commands.closeToolsPop(null);
                    })
                }, 50)

            }
        }
    };

    /**
     * 打开文件对话框
     * @param {object=}  opt_params  可选参数  eg: {accept: ".doc,.ppt"}
     */
    commands.openFileDialog = function (opt_params) {
        var defer = jQuery.Deferred();
        var fileDialog = jQuery('<input style="display:none;"  type="file" />');
        //动态创建，不用依赖于界面
        if (fileDialog.length) {
            if (opt_params) {
                for (var attr in opt_params)
                    fileDialog.attr(attr, opt_params[attr]);
            }
            fileDialog.one('change', function () {
                defer.resolve(fileDialog.val().replace(/\\/g, "/"));
            });
            fileDialog.trigger('click');
            if (opt_params) {
                for (var attr in opt_params)
                    fileDialog.removeAttr(attr);
            }
        }
        return defer.promise();
    }

    /**
     * 保存对话框
     * @param opt_params
     * @returns {*}
     */
    commands.saveFileDialog = function (opt_params) {
        opt_params = opt_params || {};
        if (!opt_params.nwsaveas)
            opt_params.nwsaveas = "";
        var defer = jQuery.Deferred();
        this.openFileDialog(opt_params).done(function (ret) {
            console.log("save file: " + ret);
            defer.resolve(ret);
        });
        return defer.promise();
    }

    //------------------------------------------------------/end/

    /**
     * 手动关闭window
     */
    commands.closeWindow = function () {
        // 用户统计
        LM.statisticsMoudleTime('4101','quit','open_close_time');

        IO.rmdir(AppContext.getCurSlidePackPath());
        appUtil.closeApp('畅言课件制作工具（播放工具）');
        //这里是发送退出消息的地方
        if(SOCKET){
            SOCKET.send({type:'logic',action:'exit',to:'main',from:SOCKETID,data:{}});
        }
        var win = gui.Window.get();
        window.ffmid && window.ffmid.kill();
        win.close(true);
    };

    /**
     * 重置state
     */
    commands.resetAppState = function () {
        setTimeout(function(){
            $('#page_waiting').hide();
        },3000);

        $('#app_state').text('');
        for (var i in Global.AppState) {
            Global.AppState[i].value = false;
        }
    };

    //设置state
    commands.setAppState = function (p, d) {
        try {
            Global.AppState[p].value = d;
            $('#app_state').text(Global.AppState[p].explain);
        } catch (err) {

        }
    };

    /**
     * 将对象的尺寸适应到屏幕内
     */
    commands.setObjSizeForStage = function (_obj) {
        //size列表
        var _size = {width: [_obj.width, DEFAULT_STAGE.width], height: [_obj.height, DEFAULT_STAGE.height]};

        var _maxName = (function a(o) {
            var _t = [];
            for (var i in o) {
                if (o[i][0] > o[i][1]) {
                    _t.push([i, o[i][0]]);
                }
            }
            if (_t.length > 1) {
                return _t[0][1] > _t[1][1] ? _t[0][0] : _t[1][0];
            } else if (_t.length > 0) {
                return _t[0][0];
            }
            return null;
        })(_size);

        if (!_maxName) {
            return false;
        } else {
            return ((DEFAULT_STAGE[_maxName] / _obj[_maxName]) * DEFAULT_OBJECT_SCALE).toFixed(2);
        }
    };

    /**
     * 设置群组对象对齐方式
     * @param _group
     * @param _align
     */
    commands.setGroupAlign = function (_group, _align) {
        //var _t = [],_l = 0;
        Global.isVariety = true;
        var _position = 0;
        switch (_align) {
            case "left":
                var _obj1 = getPosition(_group, 'left', 1);
                _position = _obj1.p;
                for (var i = 0; i < _group.length; i++) {
                    _group[i].setLeft(_position);
                }
                break;
            case "right":
                var _obj2 = getPosition(_group, 'left', 2);
                _position = _obj2.p + _obj2.w;
                for (var i = 0; i < _group.length; i++) {
                    _group[i].setLeft(_position - _group[i].width * _group[i].scaleX);
                }
                break;
            case "center":
                var _position = getAvgPosition(_group, 'left');
                /*var _ts = getPosition(_group,'left',1)
                 for(var i=0;i<_group.length;i++)
                 {
                 _group[i].setLeft(_position-(_group[i].width*_group[i].scaleX)*0.5-_ts.p);
                 }*/
                break;
            case "top":
                var _obj3 = getPosition(_group, 'top', 1);
                _position = _obj3.p;
                for (var i = 0; i < _group.length; i++) {
                    _group[i].setTop(_position);
                }
                break;
            case "buttom":
                var _obj4 = getPosition(_group, 'top', 3);
                _position = _obj4.p + _obj4.h;
                for (var i = 0; i < _group.length; i++) {
                    _group[i].setTop(_position - _group[i].height * _group[i].scaleY);
                }
                break
            case "vertical":
                break
        }

        /**
         * 取得目标对象
         * @_sort true升序
         */
        function getPosition(_obj, _type, _sort) {
            var _t = [];
            for (var a = 0; a < _obj.length; a++) {
                _t.push({t: _obj[a], p: _obj[a][_type], w: _obj[a].width * _obj[a].scaleX, h: _obj[a].height * _obj[a].scaleY});
            }
            _t.sort(function (a, b) {
                if (_sort == 1) {
                    return a.p - b.p;
                } else if (_sort == 2) {
                    return (b.p + b.w) - (a.p + a.w);
                } else if (_sort == 3) {
                    return (b.p + b.h) - (a.p + a.h);
                } else if (_sort == 4) {
                    return b.w - a.w;
                }
            })
            return _t[0];
        }

        /**
         * 取平均的值
         */
        function getAvgPosition(_obj, type) {
            var _l = getPosition(_obj, type, 4);
            for (var i = 0; i < _obj.length; i++) {
                if (_obj[i] != _l.t) _obj[i].setLeft(_l.p + ((_l.w - _obj[i].width * _obj[i].scaleX) * 0.5));
            }
            //((_w -_obj[i].width*_obj[i].scaleX)*0.5)
        }

        Global.CurrentSlide.c.renderAll();

        setTimeout(function(){
            commands.saveCtrlPath('object');
        },100)
    };

    commands.template = template;

    (function (tpl) {
        tpl.display = function (container, templateFile, args) {
            var def = $.Deferred();
            setContent(templateFile, args, function (html) {
                container && container.html(html);
                def.resolve($(html));
            });
            return def.promise();
        };

        tpl.append = function (container, templateFile, args) {
            var def = $.Deferred();
            setContent(templateFile, args, function (html) {
                var $html = $(html);
                if (container) {
                    if (!(container instanceof  jQuery))  container = $(container);
                    container.append($html);
                }
                def.resolve($html);
            });
            return def.promise();
        };

        function setContent(templateFile, args, callback) {
            try {
                IO.readFile(templateFile).done(function (content) {
                    if (content) {
                        var render = template.compile(content);
                        var html = args ? render(args) : render();
                        callback && callback(html);
                    }
                });
            } catch (err) {
                throw err;
            }
        }
    })(commands.template);




    //获取扩展名
    //更换扩展名
    commands.getExtName = function (url, ext) {
//        var result =/\.[^\.]+/.exec(url);
        var _name = null;
        _name = url.split(".");
        if (ext) {
            _name[_name.length - 1] = ext;
            _name = _name.join('.');
            return _name;
        } else {
            _name = _name[_name.length - 1];
            return ['.' + _name];
        }
    };
    /**
     * 检查路径是否包括特殊字符
     * @param url
     */
    commands.changeFilePathIsSpeailCharts = function (url, pop,close) {
        for (var i = 0; i < url.length; i++) {
            for (var c = 0; c < DEFAULT_SPECIAL_CHARTS.length; c++) {
                if (url[i] === DEFAULT_SPECIAL_CHARTS[c]) {
                    commands.resetAppState();
//                    pop || commands.showPop(commands.getErrorMsg(2014) + "<strong style='color: #ff0000'>" + url[i] + '</strong>请重命名文件', 5000);
                    pop || commands.showSelectorPop(commands.getErrorMsg(2021),function(_is){

                    },null,this,[{
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function(){
                            close?commands.closeWindow():commands.hidePop();
                        }}]
                    );
                    return false
                }
            }
        }
        return true;
    }

    /**
     *获取信息提示语
     * @param [code]  提示语key
     * @returns {*}
     */
    commands.getErrorMsg = function () {
        var _str = '';
        for (var i = 0; i < arguments.length; i++) {
            var _code = arguments[i]
            _str += DEFAULT_ERRORCODE[_code] || '';
        }
        return _str || DEFAULT_ERRORCODE[1100];
    }

    /**
     * 获取文件扩展类型
     * @param _ext  扩展名
     */
    commands.getFileExtType = function (_ext) {
        _ext = _ext.toLowerCase();
        for (var i in DEFAULT_EXT) {
            for (var m = 0; m < DEFAULT_EXT[i].length; m++) {
                if (_ext === DEFAULT_EXT[i][m]) {
                    return i;
                }
            }
        }
        return false
    }
    /**
     * 查检文件是否是要求的格式
     * @param _ext
     * @returns {*}
     */
    commands.changeFileExtType = function (_ext) {
        _ext = _ext.toLowerCase();
        for (var i in DEFAULT_EXT_SCOPE) {
            for (var m = 0; m < DEFAULT_EXT_SCOPE[i].length; m++) {
                if (_ext === DEFAULT_EXT_SCOPE[i][m]) {
                    return i;
                }
            }
        }
        return false
    };

    //取得目标路径
    commands.changeFolderToMedia = function (_src, _to, _en) {
        _src = encodeURI(AppContext.joinPath(_src));
        _src = decodeURI(_src).replace('file:///', '');
        if (_en) {
            _src = commands.changeFileName(_src)
        }
        var _tosrc = AppContext.joinPath(_to || Global.CurrentSlide.c.getCurMediaPath(), _src.substr(_src.lastIndexOf('/'), _src.length));
        var _t = _tosrc.replace(Global.CurrentSlide.c.getCurSlidePath(), '');
        return _tosrc;
    };

    //更新文件的名字
    commands.changeFileName = function(src,name)
    {
        var _src = encodeURI(AppContext.joinPath(src));
        _src = decodeURI(_src).replace('file:///', '');
        var _ts = _src.split('/');
        var _td = _ts[_ts.length - 1].split('.');

        var _tdTmp = [];
        _tdTmp[0] = _td[0];
        _tdTmp[1] = _td[_td.length - 1];

        _tdTmp[0] = name || commands.randomString(15);
        _ts[_ts.length - 1] = _tdTmp.join('.');
        _src = _ts = _ts.join('/');
        return _src;
    };

    //从地址中提取文件名
    commands.getFileNameToUrl = function(url)
    {
        var _name = url.split('\\');
        _name = _name[_name.length-1];
        _name = _name.split('.');
        _name = _name[0];
        return _name;
    };



   //-------------------------------------------回撤
    /**
     * 保存用户操作步骤
     * @param _type 操作类型
     * @param _undo 操作内容
     */
    commands.saveCtrlPath = function(_type,_undo)
    {
        if(!Global.CurrentSlide || !Global.CurrentSlide.c) return;
        if(Global.undos.length>5) Global.undos.shift();
        switch (_type)
        {
            case 'object':
//                return;
                Global.undos.push({type:_type,undo:Global.curStageJson,name:Global.CurrentSlide.c.Name});
                Global.curStageJson = Global.CurrentSlide.c.toJSON();
                break;
            case 'modified':
                /*for(var i=0;i<Global.undos.length;i++)
                {
                    if(Global.undos[i].type === 'modified')
                    {
                        Global.undos.splice(i,1)
                    }
                }*/
                Global.undos.push({type:'object',undo:Global.curStageJson,name:Global.CurrentSlide.c.Name});
                Global.curStageJson = Global.CurrentSlide.c.toJSON();
                break;
            case 'delPage':
                var _datas = {slide:[],package:[]};
                for(var m in _undo)
                {
                    for(var c=0;c<_undo[m].length;c++)
                    {
                        _datas[m].push(_undo[m][c]);
                    }
                }
                Global.undos.push({type:_type,undo:_datas});
                break;
            case "selPage":
                var _datas = Global.CurrentSlide;
                Global.undos.push({type:_type,undo:_datas});
                break;
            case "addPage":
                Global.undos.push({type:_type,undo:_undo});
                break
            case "background":
                var _datas = Global.CurrentSlide.c._canvas;
                var _src = _datas.backgroundImage;
                var _color = _datas.backgroundColor;
                Global.undos.push({type:_type,undo:{src:_src,color:_color,name:Global.CurrentSlide.c.Name}});
                break
            default:
        }
        commands.resetUndoBtn(true);
    };
    /**
     * 回撤
     * @returns {*}
     */
    commands.undo = function()
    {
        var def = $.Deferred();
        var _that =this;
        if(Global.undos.length>0)
        {
            var _json = Global.undos.pop();
            if(_json.type == 'modified')
                _json = Global.undos.pop();
            if(Global.undos.length<1) commands.resetUndoBtn();
            switch (_json.type)
            {
                case "object":
                    Global.curSelStatus = null;
                    commands.resetDeleteBtn(false);
                    commands.resetExportBtn(false);
                    commands.canvasUndoCtrl(_json,function(){
                        def.resolve();
                    },_that);
                    break
                case "delPage":
                    var _targetSlide = null;
                    for(var i=0;i<_json.undo.package.length;i++)
                    {
                        if($.inArray(_json.undo.package[i],Global.PackageJson.slides,i)<0)
                        {
                            _targetSlide =  _json.undo.package[i]
                            break;
                        }
                    }
                    commands.pagesUndoCtrl(_json,function(_thumb){
                        commands.resetAppState();
                        commands.toggerCmdBtns(true);
                        _targetSlide = commands.searchSlideById(_targetSlide || Global.PackageJson.slides[0]);
                        EventBase.fireEvent('ClickThumb',{e:_targetSlide.t,type:'undo'},true,true);
                    },_that);
                    break;
                case "selPage":
                    commands.resetAppState();
                    EventBase.fireEvent('ClickThumb',{e:_json.undo.t},true);
                    break;
                case "addPage":
                    commands.deleteSlide(_json.undo.Name);
                    break
                case "background":
                    commands.backgroundUndoCtrl(_json,function(){
                        //commands.showThumbImg(Global.CurrentSlide.t)
                        commands.resetAppState();
                        def.resolve();
                    },_that)
                    break
                default :
            }
        }else{
            def.resolve();
        }
        return def.promise();
    };

    /**
     * 画布对象的回撤操作
     * @param _json     上一步的数据
     * @param _callback 回调
     */
    commands.canvasUndoCtrl = function(_json,_callback,_agent)
    {
        if(_json.name != Global.CurrentSlide.c.Name)
        {
            _callback.call(_agent);
        }else
        {
            Global.CurrentSlide.c.loadFromJSON(_json.undo,function(e){
                Global.CurrentSlide.c._canvas.renderAll();
                Global.curStageJson = Global.CurrentSlide.c.toJSON();
                setTimeout(function(){
                    _callback.call(_agent);
                },100)
            })
        }

    }

    /**
     * 页面的回撤操作
     * @param _json
     * @param _callback
     * @param _agent
     */
    commands.pagesUndoCtrl = function(_json,_callback,_agent)
    {
        var _pages = _json.undo.slide;
        var _retPage = null;
        //找到差异的页
        for(var i=0;i<_pages.length;i++)
        {
            for(var c=0;c<Global.SlideArray.length;c++)
            {
                 if(_pages[i].c.Name!=Global.SlideArray[c].c.Name)
                 {
                     _retPage = _pages[i].t;
                     break
                 }
            }
            if(_retPage)break;
        }
		if(!_retPage) _retPage = _pages[0].t
        var _thumbBox = $('#pageArea_list');
        _thumbBox.html('');
        for(var i=0;i<_pages.length;i++)
        {
            _pages[i].t.add(_thumbBox,1);
//            _thumbBox.append(_pages[i].t.content);
        }
        Global.CurrentSlide = null;
        if($('#notSlide_add'))
        {
            $('#notSlide_add').remove();
        }
        Global.SlideArray = _json.undo.slide;
        Global.PackageJson.slides =_json.undo.package;
        Global.CurrentSlide = Global.SlideArray[0];
        IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson)).done(function(){
            _callback.call(_agent,_retPage);
        });
    };

    /**
     * 背景设置回撤
     * @param _json
     * @param _callback
     * @param _agent
     */
    commands.backgroundUndoCtrl = function(_json,_callback,_agent)
    {

        if(_json.undo.src){
            Global.DefaultBackground.color = null;
            Global.CurrentSlide.c.setBackgroundImage(_json.undo.src);
        }
        else{
            Global.CurrentSlide.c._canvas.backgroundImage = null;
            Global.CurrentSlide.c._canvas.setBackgroundColor(_json.undo.color);
        }
        Global.CurrentSlide.c.renderAll();
        setTimeout(function(){

            _callback.call(_agent)
        },100)
    };

    /**
     * 添加或取消多选对象
     * @param _tar
     */
    commands.addSelSlides = function(_tar)
    {
        if(Global.selSlides.length<=0)
        {
            Global.selSlides.push(Global.CurrentSlide.t);
        }
        for(var i = 0;i<Global.selSlides.length;i++)
        {
            var _cur = Global.selSlides[i].content;
            if(_cur.attr('id') === _tar.content.attr('id'))
            {
                Global.selSlides.splice(i,1);
                _cur.removeClass('current current2');
                return true
            }
        }

        Global.selSlides.push(_tar);
        return false;
    };


    //---------------------------------/end/



    /**
     * 对比整个包去掉未使用到的文件夹
     */
    commands.ratioPackageFiles = function()
    {
        var def = jQuery.Deferred();
        var _idx = 0;
        function _d()
        {
            var _slides = Global.SlideArray[_idx].c;
            //var _files =IO.readFileList(_slides.getCurMediaPath());
            var _json = JSON.parse(IO.readFileSync(_slides.getCurJsonPath()));
            var _nfiles = [];
            o(_json.canvas.objects,_nfiles);
            if(_json.canvas.background && _json.canvas.background.source)
            {
                var _f1 = _json.canvas.background.source.split('/');
                _nfiles.push(_f1[_f1.length-1]);
            }
            if(_json.canvas.backgroundImage && _json.canvas.backgroundImage.src)
            {
                var _f2 = _json.canvas.backgroundImage.src.split('/');
                _nfiles.push(_f2[_f2.length-1]);
            }
            r(_json.rels,_nfiles);
            IO.removeCorpseFile(_slides.getCurMediaPath(),_nfiles).done(function(){
                _idx++;
                if(_idx<Global.SlideArray.length)
                {
                    _d();
                }else
                {
                    def.resolve(true);
                }
            })
        }

        //找到canvas对像里的所有文件
        function o(_obj,_arr)
        {
            for(var i=0;i<_obj.length;i++)
            {
                if(_obj[i].src && _obj[i].src!='undefined')
                {
                    var _srcs = _obj[i].src.split('/');
                    if(_srcs[0] === 'media' && _srcs.length == 2)
                    {
                        _arr.push(_srcs[1]);
                    }
                }
            }
        }
        //找到rela里的所有文件
        function r(_obj,_arr)
        {
            for(var i=0;i<_obj.length;i++)
            {
                var _f1= _obj[i].src.split('/');
                if(_obj[i].title==='热区' && _f1.length>=4)
                    _arr.push(_f1[_f1.length-2]);
                else
                    _arr.push(_f1[_f1.length-1]);
            }
        }
        _d();
        return def.promise();
    };

    /**
     *  查检当前有没有可用的slide
     */
    commands.notActiveSlide = function()
    {
        if(!Global.CurrentSlide)
        {
            commands.showPop(commands.getErrorMsg(1100))
            return false;
        }
        return true;
    };

    /**
     * 设置撤销按钮
     * @param _ar
     */
    commands.resetUndoBtn = function(_ar){
        if(_ar)
        {
            $('#btn_undo>img').attr('src','editor/assert/images/menu_revoke.png');
        }else
        {
            Global.undos = [];
            $('#btn_undo>img').attr('src','editor/assert/images/menu_revoke_disable.png');
        }

    }

    /**
     * 设置删除按钮
     * @param _ar
     */
    commands.resetDeleteBtn = function(_ar){
        if(_ar)
        {
            $("#btn_delete>img").attr("src","editor/assert/images/menu_delete.png");
        }else
        {
            $("#btn_delete>img").attr("src","editor/assert/images/menu_delete_disable.png");
        }
    }

    /**
     * 设置导出按钮
     * @param _arg
     */
    commands.resetExportBtn = function (_arg) {
        if(_arg){
            $("#btn_export>img").attr("src","editor/assert/images/menu_export.png");
        } else {
            $("#btn_export>img").attr("src","editor/assert/images/menu_export_disable.png");
        }
    }

    commands.checkDeleteBtn = function(){
        if($('#btn_delete>img').attr("src") == "editor/assert/images/menu_delete_disable.png"){
            return false;
        }
        else{
            return true;
        }
    }

    //按钮样式控制。全灰
    commands.toggerCmdBtns = function(_is)
    {
        var _btns = ['btn_save','btn_open_wgt','btn_savemore','btn_upLoad','btn_export','btn_delete','btn_hdmb','btn_bubble','btn_img','btn_media','btn_text','path_btn','btn_bg']
        for(var i=0;i<_btns.length;i++)
        {
            var _btn = $('#'+_btns[i]).find('img');
            var _input = $('#'+_btns[i]).find('input');
            var _src = _btn.attr('src');
            var _srcs = _src.split('.');
            if(!_is)
            {
                var _name =_srcs[_srcs.length-2].replace('_disable','');
                _srcs[_srcs.length-2] = _name+'_disable';
                if(_input)_input.css('display','none');
            }else
            {
                _srcs[_srcs.length-2] =_srcs[_srcs.length-2].replace('_disable','');
                if(_input)_input.css('display','');
            }

            _src = _srcs.join('.')
            _btn.attr('src',_src);
        }

    }

    //没有页的情况下按钮显示状态
    commands.addNotSlideMask = function(){

        if(Global.SlideArray.length<1)
        {
            commands.toggerCmdBtns(false);
            $('#stageArea').append('<div id="notSlide_add" style="z-index:109;width: 100%;height: 100%;position: relative;left: 0;top: 0;"><span style="text-align: center;display: block;width: 100%;font-size: 25px;top: 50%;position: relative;">点击舞台区添加一张空白页</span></div>')
            //$('#cmd_menu_box').append('<div style="z-index: 2;height: 100%;position: absolute;right: 0;width: 64%;"></div>');
            $('#notSlide_add').on('click',function(e){
                commands.toggerCmdBtns(true);
                EventBase.fireEvent('elementPageAdd');
                $('#notSlide_add').remove();
            })
        }
    }


    /*
    * 文本编辑器
    * 直接套用型试
    * */
    commands.renderTextEditor=function(_tar){
        $(_tar).off();
        var _content = _tar.innerHTML;
        $(_tar).html('');
        var editor = UE.getEditor(_tar.id,{
          initialFrameWidth:'100%',
          initialFrameHeight: '148',
          UEDITOR_HOME_URL:'share/assert/js/3rdparty/ueditor/'
        });

        var _textMask = '<div id="ue_text_mask" class="ue-text-mask"></div>';
        $(_tar).parent().append(_textMask);
        editor.addListener('ready',function(e){
            editor.setContent(_content);
            editor.focus(false);
            $(_tar).css('overflow-y','');
        })
//        window.addEventListener('click')
        $('#ue_text_mask').on('click',function(e){
            $(this).remove();
            _content = editor.getContent();
            editor.destroy();
            $(_tar).on('click',function(e){
                commands.renderTextEditor(this);
            })
        })
       editor.addListener('destroy',function(e){
           $(_tar).html(_content);
		   $(_tar).css('overflow-y','auto');
           $(_tar).css('height','150px');
        });
    };

    commands.textEditorDialog = function(_tar)
    {
        var _str = _tar.innerHTML;
//        $(_tar).html('');
        var _dialog =$('<div id="ue_text_dialog" style="padding-top: 15%" class="modal in" tabindex="-1" role="dialog"><div class="modal-dialog test_temp">' +
            '<div id="ue_text_editor" style="min-height: 200px"></div>' +
            '<div class="test_temp_btns hot_area_func">' +
            '<a href="javascript:;" id="ut_text_submit" class="test_temp_btn_nor fr" title="确定">确定</a>' +
            '</div>' +
            '</div></div>');
        $('body').append(_dialog);

        _dialog.on('hide.bs.modal',function(e){
            _dialog.remove();
        });
        _dialog.modal({show: true,keyboard:false,backdrop:false});
        var editor = UE.getEditor('ue_text_editor',{
            initialFrameWidth:'100%'
        });
        editor.addListener('ready',function(e){
            editor.setContent(_str);
        });
        $('#ut_text_submit').on('click',function(e){
            $(_tar).html(editor.getContent());
            editor.destroy();
            $('#ue_text_dialog').remove()
            $('#edui_fixedlayer').remove()
        })
        UE.registerUI('close', function(editor, uiName) {
            //注册按钮执行时的command命令，使用命令默认就会带有回退操作
            editor.registerCommand(uiName, {
                execCommand: function() {
                    editor.destroy();
                    $('#ue_text_dialog').remove()
                    $('#edui_fixedlayer').remove()
                }
            });
            //创建一个button
            var btn = new UE.ui.Button({
                //按钮的名字
                name: uiName,
                //提示
                title: uiName,
                //添加额外样式，指定icon图标，这里默认使用一个重复的icon
                cssRules: 'background-position: -500px 0;',
                //点击时执行的命令
                onclick: function() {
                    //这里可以不用执行命令,做你自己的操作也可
                    editor.execCommand(uiName);
                }
            });
            //当点到编辑内容上时，按钮要做的状态反射
            editor.addListener('selectionchange', function() {
                var state = editor.queryCommandState(uiName);
                if (state == -1) {
                    btn.setDisabled(true);
                    btn.setChecked(false);
                } else {
                    btn.setDisabled(false);
                    btn.setChecked(state);
                }
            });
            //因为你是添加button,所以需要返回这个button
            return btn;
        });

    }

    /**
    * 返回页面已选widget对象的绝对路径
    * @returns {*}
    */
    commands.getCurrentActiveObjectPath = function () {
        var slidePath = Global.CurrentSlide.c.getCurSlidePath();
        var relPath = Global.CurrentSlide.c.getActiveObject().rinfo.src;
        return paths.join(slidePath,relPath);
    }

    /**
     * 返回当前选中gif对象的绝对路径
     */
    commands.getCurrentActiveGifPath = function () {
        var def = $.Deferred();
        var slidePath = Global.CurrentSlide.c.getCurSlidePath();
        var relPath = Global.CurrentSlide.c.getActiveObject().rinfo.src;

        var metaJson = paths.join(paths.join(slidePath, relPath), 'meta.json');
        IO.readFile(metaJson).done(function (content) {
            var cmd = JSON.parse(content);
            var gifPath = paths.join(paths.join(slidePath, relPath), cmd.imgSrc);
            def.resolve(gifPath);
        });
        return def.promise();
    }

    /**
     * 删除一个slide
     * @param _slide slidename
     */
    commands.deleteSlide = function(_slide)
    {
        for (var i = 0; i < Global.SlideArray.length; i++) {
            if (Global.SlideArray[i].c.Name == _slide) {
                var _dpath = Global.SlideArray[i].c.getCurSlidePath();
                Global.SlideArray[i].t.content.remove();
                $('#stageArea').html('');
                Global.SlideArray[i].c.clear();
                delete  Global.SlideArray[i];
                Global.KeyLists = [];
                Global.CurrentSlide = null;
                Global.SlideArray.splice(i, 1);
                Global.PackageJson.slides.splice(i, 1);
//                _slide.content.remove();
                //IO.rmdir(_dpath);
                IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson));
                if (Global.SlideArray.length <= 0) {
                    //$('#btn_add')[0].click();
                } else {
                    EventBase.fireEvent('updateSlide',{index:i == 0 ? 0 : --i})
//                    main.updateStage(i, 5);
                }
                return;
            }
        }
    }

    /**
     * 写当前slide.json
     */
    commands.writeSlideJson = function(){
        commands.setAppState('init',true);
        IO.writeFile(Global.CurrentSlide.c.getCurJsonPath(), Global.CurrentSlide.c.toJSON()).done(function (err) {
            commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function(){
                commands.resetAppState();
            });
        });
    }
    exports.commands = commands;
});

