/**
 * Created by W.J.Chang on 2014/7/15.
 */

define(function (require, exports, modules) {

    var path = require('../../../../../share/assert/js/path');
    var tts = require('editor/assert/js/addon/msptts');
    var urlCheck = require('editor/assert/js/addon/urlCheck');
    var fsUtil = require('editor/assert/js/utils/fileSystemUtil');

    var io = require('../../../../../share/assert/js/ioutil_desktop.js').IOUtil;
    var commands =   require('editor/assert/js/utils/commands').commands;
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var isOnline=false; //是否联网
    var bgimgPath = null;
    var dlg = null;
    var dlg_loading = null;

    seajs.use('./editor/assert/js/3rdparty/html2canvas.js');
    seajs.use('./editor/assert/js/utils/dialogutil.js');
    seajs.use('./editor/assert/js/utils/fileSystemUtil.js');
    seajs.use('./editor/assert/style/speechapp/speech_scene.css');

    fabric.Situdlg.prototype.showEditDialog = function (opt) {
        var _self = this;

        if(opt && opt.src){
            if (opt.src.indexOf(Global.CurrentSlide.c.getCurSlidePath()) != -1) {
                opt.src = opt.src.replace(Global.CurrentSlide.c.getCurSlidePath()+"\/","");
            }
        }

        console.log('situdlg edit fired!', opt);

        if ($('#modal-content')) {
            $('#modal-content').remove();
        }

        if ($('#modal_content_loading')) {
            $('#modal_content_loading').remove();
        }

        dlg_loading = $('<div id="modal_content_loading" class="modal fade in" tabindex="-1" role="dialog" ' +
            'style="padding-top: 22%; z-index:9999999; overflow-x: hidden; display:none;" aria-hidden="false">' +
            '<div class="pop_warp pop_tips" style="height: 149px;">' +
            '<div class="pop_tit"><span class="fl">温馨提示</span>' +
            '<div class="w_func fr" id="btn_loading_close"><a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
            '</div>' +
            '</div>' +
            "<div style='text-align: center; width:100%; height: 85px; font-family: microsoft yahei; font-size: 16px; color: #898989'>" +
            "<img src='editor/assert/images/page-loader.gif' style='margin-left: auto; margin-right: auto; margin-top: 15px; height: 30px; width:30px;'/>" +
            "<p id='loading'>正在生成卡片，请稍候...</p></div>" +
            '<div class="pop_btn_box t_center" id="pop_btns_box">' +
            '<a href="javascript:void(0)" class="pop_btn" id="btn_loading_yes"><span>关闭</span></a>' +
            '</div>' +
            '</div>' +
            '</div>'
        );

        $('body').append(dlg_loading);

        dlg_loading.find('#btn_loading_close').bind('click', function () {
            dlg_loading.hide();
        });

        dlg_loading.find('#btn_loading_yes').bind('click', function () {
            dlg_loading.hide();
        });

        dlg = $('<div id="modal-content" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog">' +
            '<div class="test_temp" style="width: 660px;">' +

            '<div class="pop_tit">' +
            '<span class="fl">'+
            '英文情景对话评测卡片' +
            '</span>'+
            '<div class="w_func fr"><a href="javascript:;" title="关闭" data-dismiss="modal" class="w_func_close"></a></div>'+
            '</div>' +

            '<div class="modal-body" style="margin: 0;padding: 0;">' +

            '<div class="scene" style="display: none;background-color: #ffffff;" id="prev_situ_node">' +

            '<div class="scene_cont" style="height:330px; overflow-y:auto;" id="prev_situ_node_scene">' +
            '<image id="inner_image" />'+
            '<ul class="scene_list" id="pre_list_node" style="position: absolute;width: 95%;z-index: 200;height:300px; overflow-y:auto;">' +

            '</ul>' +
            '</div>' +

            '<div class="scene_func clearfix">' +
            '<span class="smile_icon"></span>' +
            '<div class="scene_func_detail" >' +
            '<a href="javascript:;">' +
            '<img alt="开始对话" src="editor/assert/images/speechapp/func_img1.png" />' +
            '开始对话' +
            '</a>' +
            '<a href="javascript:;">' +
            '<img alt="示范朗读" src="editor/assert/images/speechapp/func_img2.png" />' +
            '示范朗读' +
            '</a>' +
            '<a href="javascript:;">' +
            '<img alt="对话回放" src="editor/assert/images/speechapp/func_img3.png" />' +
            '对话回放' +
            '</a>' +
            '<a href="javascript:;">' +
            '<img alt="对话选项" src="editor/assert/images/speechapp/func_img4.png" />' +
            '对话选项' +
            '</a>' +
            '</div>' +
            '</div>' +

            '</div>' +

            '<div id="situ_area_node">' +
            '<div class="tst_temp_step_situ tst_temp_conversation">' +

            '<div id="situ_node"  style="height:240px; overflow-y:auto;background-color: #ffffff">' +

            '<div class="tst_temp_row_a">' +
            '<label for="conversation_1" style="display: inline-block;">A：</label>' +
            '<input type="text" class="form-control roleAText" style="display: inline-block;width: 450px;height: 28px;"/>' +
            '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
            '</div>' +

            '<div class="tst_temp_row_b">' +
            '<label for="conversation_2" style="display: inline-block;">B：</label>' +
            '<input type="text" class="form-control roleBText" style="display: inline-block;width: 450px;height: 28px;"/>' +
            '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
            '</div>' +

            '<div class="tst_temp_row_a">' +
            '<label for="conversation_1" style="display: inline-block;">A：</label>' +
            '<input type="text" class="form-control roleAText" style="display: inline-block;width: 450px;height: 28px;"/>' +
            '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
            '</div>' +

            '<div class="tst_temp_row_b">' +
            '<label for="conversation_2" style="display: inline-block;">B：</label>' +
            '<input type="text" class="form-control roleBText" style="display: inline-block;width: 450px;height: 28px;"/>' +
            '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
            '</div>' +

            '</div>' +
            '</div>' +

            '<a href="javascript:;" id="situ_add_conv_btn" class="add_conv_btn" style="margin-left: ;">添加一组对话</a>' +
            '<p style="padding: 0 15px;color: #ff5a00; font-size: 14px;" id="situ_prew_tip">温馨提示：情景对话只支持英文。</p>'+
            '</div>' +
            '</div>' +


            '<div class="pop_btn_box">' +
            '<a id="situ_nextBtn" href="javascript:;" class="pop_btn fr mrmt " ><span class="pop_btn_s2">下一步</span></a>' +
            '<a id="situ_situCreate" href="javascript:;" class="pop_btn fr mrmt " style="display: none; "><span class="pop_btn_s2">完成</span></a>' +
            '<a id="situ_insertPic" href="javascript:;" class="pop_btn fr mrmt " style="display: none; "><span class="pop_btn_s2">选择背景图</span></a>' +
            '<a id="situ_preBtn" href="javascript:;" class="pop_btn mrmt " style="display: none;float: left;"><span class="pop_btn_s2">上一步</span></a>' +
            '</div>' +

            '</div>' +
            '</div>');

        var top=(window.innerHeight-430)/2;
        var left = (window.innerWidth - 660)/2;
        dlg.css("paddingTop",top);
        dlg.css("paddingLeft",left);

        $('body').append(dlg);

        dlg.on('hidden.bs.modal', function () {
            bgimgPath = null;
        });

        // 新加一组对话
        dlg.find("#situ_add_conv_btn").bind('click', function () {
            $('#situ_node').append(
                    '<div class="tst_temp_row_a">' +
                    '<label for="conversation_1" style="display: inline-block;">A：</label>' +
                    '<input type="text" class="form-control roleAText" style="display: inline-block;width: 450px;height: 28px;"/>' +
                    '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
                    '</div>' +

                    '<div class="tst_temp_row_b">' +
                    '<label for="conversation_2" style="display: inline-block;">B：</label>' +
                    '<input type="text" class="form-control roleBText" style="display: inline-block;width: 450px;height: 28px;"/>' +
                    '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
                    '</div>'
            )
        });

        // 插入背景图片
        dlg.find("#situ_insertPic").bind('click', function () {
            var _self = this;

            var options = {multiple: false, accept: "image/jpg, image/jpeg, image/bmp, image/png"};
            DialogUtil.openFileDialog(options).done(function (filePath) {
                console.log(filePath);
                bgimgPath = filePath;

                if(!commands.changeFilePathIsSpeailCharts(bgimgPath)) {
                    bgimgPath = null;
                }
                setBackground();
            });
        });

       // 点击下一步
        dlg.find("#situ_nextBtn").bind('click', function () {
            $('#loading').text('正在检查网络连接...');
            dlg_loading.show();
            urlCheck.pingBaidu().done(function(ret) {
                console.log("isOnline:"+ret);
                isOnline = ret;
                if(!ret) {
                    $('#situ_prew_tip').text('需要联网！');
                } else {
                    genPreview();
                }

                dlg_loading.hide();
            });
        });

        // 键盘按键抬起事件
//        dlg.find("#situ_node").bind('keyup', function () {
//            $('#situ_prew_tip').text('温馨提示：情景对话只支持英文。');
//        });

        dlg.on('hidden.bs.modal',function() {
            Global.isEditing = false;
        });

        // 点击修改
        dlg.find("#situ_preBtn").bind('click', function () {
            $('#situ_area_node').show();
            $('#prev_situ_node').hide();
            $('#situ_preBtn').hide();
            $('#situ_situCreate').hide();
            $('#situ_insertPic').hide();
            $('#situ_nextBtn').show();

            var top=(window.innerHeight-430)/2;
            $('#modal-content').css('paddingTop',top);
        });

        // 点击完成
        dlg.find("#situ_situCreate").bind('click', function () {
            var sentInfo = {"roleATextArr": [], "roleBTextArr": []};

            $('.roleAText').each(function () {
                var text = $(this).val();
                text = text.replace(/[^a-zA-Z\'\s,\.\?!\uff0c]/g, '');
                text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');

                sentInfo.roleATextArr.push(text);
            });

            $('.roleBText').each(function () {
                var text = $(this).val();
                text = text.replace(/[^a-zA-Z\'\s,\.\?!\uff0c]/g, '');
                text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');
                sentInfo.roleBTextArr.push(text);
            });

            $('#loading').text("正在生成卡片，请稍候...");
            dlg_loading.show();

            html2canvas($('#prev_situ_node'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    _self.saveToFile(sentInfo, data,opt).done(function(){
                        dlg.modal('hide');
                    });
                }
            });
        });


        dlg.modal({show: true,backdrop : "static"});

        // 产生预览
        function genPreview() {
            // 构造对话集合
            var sentInfo = {"roleATextArr": [], "roleBTextArr": []};
            // 收集A ，过滤中文和空格
            $('.roleAText').each(function () {
                var text = $(this).val();
                text = text.replace(/[^a-zA-Z\'\s,\.\?!\uff0c]/g, '');
                text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');

                sentInfo.roleATextArr.push(text);
            });

            // 收集B ，过滤中文和空格
            $('.roleBText').each(function () {
                var text = $(this).val();
                text = text.replace(/[^a-zA-Z\'\s,\.\?!\uff0c]/g, '');
                text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');
                sentInfo.roleBTextArr.push(text);
            });

            var isEmpty = true;
            for(var i=0; i<sentInfo.roleATextArr.length;i++) {
                if(sentInfo.roleATextArr[i]!="" || sentInfo.roleBTextArr[i] !="") {
                    isEmpty = false;
                }
            }

            if(isEmpty) {
                $('#situ_prew_tip').text('不能全为空！');
                return;
            }

            $('#situ_area_node').hide();
            $('#prev_situ_node').show();
            $('#situ_preBtn').show();
            $('#situ_situCreate').show();
            $('#situ_nextBtn').hide();
            $('#situ_insertPic').show();

            var top=(window.innerHeight-467)/2;
            $('#modal-content').css('paddingTop',top);

            // 先清空一次预览的对话
            $('#pre_list_node').empty();

            // 构造预览对话
            for(var i=0; i<sentInfo.roleATextArr.length;i++) {

                // 只有A
                if(sentInfo.roleATextArr[i]!=""&&sentInfo.roleBTextArr[i] == "") {
                    $('#pre_list_node').append('<li class="clearfix">' +
                        '<div class="scene_question">'+
                        '<div class="scene_quest_m">'+sentInfo.roleATextArr[i]+'</div>'+
                        '<em class="scene_quest_tip"></em>'+
                        '</div>'+
                        '</li>');
                }

                // 只有B
                if(sentInfo.roleATextArr[i] == "" && sentInfo.roleBTextArr[i]!=""){
                    $('#pre_list_node').append('<li class="clearfix">' +
                        '<div class="scene_answer">'+
                        '<div class="scene_answer_m">'+sentInfo.roleBTextArr[i]+'</div>'+
                        '<em class="scene_answer_tip"></em>'+
                        '</div>'+

                        '</li>');
                }

                // 有A,有B
                if(sentInfo.roleATextArr[i]!="" && sentInfo.roleBTextArr[i]!="") {
                    $('#pre_list_node').append('<li class="clearfix">' +
                        '<div class="scene_question">'+
                        '<div class="scene_quest_m">'+sentInfo.roleATextArr[i]+'</div>'+
                        '<em class="scene_quest_tip"></em>'+
                        '</div>'+
                        '<div class="scene_answer">'+
                        '<div class="scene_answer_m">'+sentInfo.roleBTextArr[i]+'</div>'+
                        '<em class="scene_answer_tip"></em>'+
                        '</div>'+
                        '</li>');
                }
            }

            setBackground();
        }

        //设置背景图片
        function setBackground(){
            if(bgimgPath) {

                var encodeBgImgPath = decodeURI(encodeURI(bgimgPath.replace(/\\/gi,'/')));
                console.log(encodeBgImgPath);

                $('#inner_image').prop('src',encodeBgImgPath+"?"+ Math.random());
            }
        }

        $("#situ_node").on({
            "mouseover": function () {
                $('div',this).css('display','inline-block');
            },
            "mouseleave":function() {
                $('div',this).hide();
            }

        },".tst_temp_row_a");

        $("#situ_node").on({
            "keyup": function () {
               var text = $(this).val().trim();
               if(text.length >= 200) {
                   $('#situ_prew_tip').text('超出字符限制，单句最长200字符');
                   text = text.substr(0,200);
                   $(this).val(text);
               }
               console.log();
            }
        },".tst_temp_row_a input");

        $("#situ_node").on({
            "keyup": function () {
                var text = $(this).val().trim();
                if(text.length >= 200) {
                    $('#situ_prew_tip').text('超出字符限制，单句最长200字符');
                    text = text.substr(0,200);
                    $(this).val(text);
                }
                console.log();
            }
        },".tst_temp_row_b input");


        $("#situ_node").on({
            "mouseover": function () {
                $('div',this).css('display','inline-block');
            },
            "mouseleave":function() {
                $('div',this).hide();
            }

        },".tst_temp_row_b");

        $("#situ_node").on({
            "click": function () {
                $(this).parent().find('input').val("");
                $(this).parent().hide();
            }
        },".situ_dlg_btn_close");

        $("#situ_node").on({
            "focus": function () {
                setTimeout(function(){
                    $('#situ_prew_tip').text('温馨提示：情景对话只支持英文。');
                },1500);
            }
        },"input");

        if(opt) {
            try
            {
                var metaJson;
                if (opt.src.indexOf(Global.CurrentSlide.c.getCurSlidePath()) == -1) {
                    metaJson = path.join(Global.CurrentSlide.c.getCurSlidePath(), opt.src, 'meta.json');
                }
                else {
                    metaJson = path.join(opt.src, 'meta.json');
                }
                io.readFile(metaJson).done(function(ret) {
                    var metaObj = JSON.parse(ret);
                    if(metaObj['backgroundimg']) {
                        if (opt.src.indexOf(Global.CurrentSlide.c.getCurSlidePath()) == -1) {
                            bgimgPath = path.join(Global.CurrentSlide.c.getCurSlidePath(), opt.src, metaObj['backgroundimg']);
                        }
                        else {
                            bgimgPath = path.join(opt.src, metaObj['backgroundimg']);
                        }
                    }

                    console.log(ret);
                    console.log(bgimgPath);
                    $('#situ_node').empty();

                    var sentInfo = {"roleATextArr": [], "roleBTextArr": []};
                    var index = 0;
                    while(index < metaObj.sens.length) {
                        var role = metaObj.sens[index].role;
                        var text = metaObj.sens[index].text;
                        if(index+1<metaObj.sens.length && role == "A" && metaObj.sens[index+1].role=="B") {
                            sentInfo.roleATextArr.push(text);
                            sentInfo.roleBTextArr.push(metaObj.sens[index+1].text);

                            index += 2;
                            continue;
                        }

                        if(index+1<metaObj.sens.length && role == "A" && metaObj.sens[index+1].role=="A") {
                            sentInfo.roleATextArr.push(text);
                            sentInfo.roleBTextArr.push("");

                            index += 1;
                            continue;
                        }

                        if(index+1<metaObj.sens.length && role == "B" && metaObj.sens[index+1].role=="A") {
                            sentInfo.roleATextArr.push("");
                            sentInfo.roleBTextArr.push(text);

                            index += 1;
                            continue;
                        }

                        if(index+1<metaObj.sens.length && role == "B" && metaObj.sens[index+1].role=="B") {
                            sentInfo.roleATextArr.push("");
                            sentInfo.roleATextArr.push("");
                            sentInfo.roleBTextArr.push(text);
                            sentInfo.roleBTextArr.push(metaObj.sens[index+1].text);
                            index += 2;
                            continue;
                        }

                        if(index+1==metaObj.sens.length && role == "B") {
                            sentInfo.roleATextArr.push("");
                            sentInfo.roleBTextArr.push(text);
                            index += 1;
                            continue;
                        }

                        if(index+1==metaObj.sens.length && role == "A") {
                            sentInfo.roleATextArr.push(text);
                            sentInfo.roleBTextArr.push("");
                            index += 1;
                            continue;
                        }
                    }
                    console.log(sentInfo);

                    for(var i=0; i < sentInfo.roleATextArr.length;i++) {
                        $('#situ_node').append('<div class="tst_temp_row_box">' +
                                '<div class="tst_temp_row_a">' +
                                '<label for="conversation_1" style="display: inline-block;">A：</label>' +
                                '<input type="text" class="form-control roleAText" style="display: inline-block;width: 450px;height: 28px;" value="'+sentInfo.roleATextArr[i]+'"/>' +
                                '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
                                '</div>' +
                                '<div class="tst_temp_row_b">' +
                                '<label for="conversation_2" style="display: inline-block;">B：</label>' +
                                '<input type="text" class="form-control roleBText" style="display: inline-block;width: 450px;height: 28px;" value="'+sentInfo.roleBTextArr[i]+'"/>' +
                                '<div class="situ_dlg_btn_close" style="display:none;width: 20px;height: 20px;position:relative;top:5px;float: right;right: 80px;"></div>' +
                                '</div>' +
                                '</div>'
                        )
                    }
                });
            } catch (e) {
                console.log("重新读取meta.json文件异常:"+e);
            }
        }

        urlCheck.pingBaidu().done(function(ret) {
            console.log("isOnline:"+ret);
            isOnline = ret;
        });

    };

    fabric.Situdlg.prototype.saveToFile = function (info, data, opt) {
        var _self = this;
        var def = $.Deferred();

        var s = Global.CurrentSlide.c;

        if (!data || !info) {
            console.log('卡片合成失败：没有返回结果或生成缩略图失败');
            dlg_loading.hide();
            def.resolve();
        }
        Global.isVariety = true;
        if(opt) {
            urlCheck.pingBaidu().done(function(ret) {
                if(ret) {
                    var wdir = s.getCurSlidePath()+'/' + opt.src;
                    var matePath = path.join(wdir, 'meta.json');
                    //FileSystemUtil.deleteFiles(wdir,['.wav','.mp3']);
                    var thumbImagePath = path.join(wdir, 'thumbnail.png');

                    var speecher = 'mary';
                    var audioPath = wdir;

                    var wavInfo = info;

                    var bgfile = "";
                    if(bgimgPath) {
                        var extName = path.extname(bgimgPath);
                        bgfile = 'gbimage'+extName;
                        io.copyFileSync(bgimgPath,path.join(wdir,bgfile));
                    }
                    bgimgPath = null;

                    var metaJson = {"cardtype": "situ", "thumbnial": "thumbnail.png", "title": "", "keywords": "test", "backgroundimg": bgfile, "sens": []};
                    for (var i = 0; i < wavInfo.roleATextArr.length; i++) {
                        if (wavInfo.roleATextArr[i].length) {
                            var tempObjA = {"role": "A", "text": wavInfo.roleATextArr[i], "audio": "A" + i + ".mp3", "hotarea": []};
                            metaJson.sens.push(tempObjA);
                        }

                        if (wavInfo.roleBTextArr[i].length) {
                            var tempObjB = {"role": "B", "text": wavInfo.roleBTextArr[i], "audio": "B" + i + ".mp3", "hotarea": []};
                            metaJson.sens.push(tempObjB);
                        }
                    }

                    if(metaJson.sens.length==0) {

                        dlg_loading.hide();
                        bgimgPath = null;

                        return;
                    }

                    // 合成语音
                    tts.situTTSWithTryTimes(metaJson, speecher, audioPath,3).done(function (ret) {
                        console.log(ret);
                        var resultJsonArr = ret.resultJsonArr;
                        var audioFlag = true;
                        for(var i=0;i<resultJsonArr.length;i++) {
                            if(resultJsonArr[i] == "") {
                                audioFlag = false;
                                break;
                            }
                            var retObj = JSON.parse(resultJsonArr[i]);
                            console.log(retObj['audioFlag']);
                            if(retObj['audioFlag'] == 'false' || retObj['result']=="") {
                                audioFlag = false;
                                break;
                            }
                        }
                        console.log(audioFlag);
                        if(audioFlag == false) {
                            $('#loading').text('引擎错误，合成失败...');
                            dlg_loading.show();
                            def.resolve();
                            setTimeout(function() {
                                dlg_loading.hide();
                                commands.showSelectorPop("卡片生成失败，请重新生成。",function(){
                                    commands.hidePop();
                                },null,this,[
                                    {
                                        label: '确定',
                                        cssClass: 'btn-primary',
                                        action: function () {
                                            commands.hidePop();
                                            dlg.modal('show');
                                        }
                                    }
                                ]);
                            },3000);

                        }else {
                            io.writeFile(matePath, JSON.stringify(metaJson));

                            io.writeIMG(thumbImagePath, data).done(function () {

                                _self.setSrc(thumbImagePath+"?"+Math.random(), function () {
                                    _self.width = 905;
                                    _self.height = 590;

                                    s.renderAll();
                                    console.log(s.toJSON());
                                    setTimeout(function(){
                                        commands.showThumbImg(Global.CurrentSlide.c._canvas);
                                    },100);
                                    def.resolve();
                                    dlg_loading.hide();
                                });
                            });
                        }
                    });
                }else {
                    $('#loading').text('无法联网，合成失败...');
                    dlg_loading.show();
                    def.resolve();
                    setTimeout(function() {
                        dlg_loading.hide();
                    },3000);
                }
            });
        } else {
            urlCheck.pingBaidu().done(function(ret) {
                if(ret) {

                    _self.id = s.NewWId(_self.type);

                    var wdir = path.join(s.getCurSlidePath(), 'media', _self.id);
                    //FileSystemUtil.deleteFiles(wdir,['.wav','.mp3']);
                    var relDir = path.join('media', _self.id);

                    console.log(wdir);

                    io.mkdir(wdir).done(function () {

                        var matePath = path.join(wdir, 'meta.json');
                        var thumbImagePath = path.join(wdir, 'thumbnail.png');

                        var speecher = 'mary';
                        var audioPath = wdir;

                        var wavInfo = info;

                        var bgfile = "";
                        if(bgimgPath) {
                            var extName = path.extname(bgimgPath);
                            bgfile = 'gbimage'+extName;
                            io.copyFileSync(bgimgPath,path.join(wdir,bgfile));
                        }
                        bgimgPath = null;

                        var metaJson = {"cardtype": "situ", "thumbnial": "thumbnail.png", "title": "", "keywords": "test", "backgroundimg": bgfile, "sens": []};
                        for (var i = 0; i < wavInfo.roleATextArr.length; i++) {
                            if (wavInfo.roleATextArr[i].length) {
                                var tempObjA = {"role": "A", "text": wavInfo.roleATextArr[i], "audio": "A" + i + ".mp3", "hotarea": []};
                                metaJson.sens.push(tempObjA);
                            }

                            if (wavInfo.roleBTextArr[i].length) {
                                var tempObjB = {"role": "B", "text": wavInfo.roleBTextArr[i], "audio": "B" + i + ".mp3", "hotarea": []};
                                metaJson.sens.push(tempObjB);
                            }
                        }

                        if(metaJson.sens.length==0) {
                            dlg_loading.hide();
                            return;
                        }

                        // 合成语音
                        tts.situTTSWithTryTimes(metaJson, speecher, audioPath,3).done(function (ret) {
                            console.log(ret);
                            var resultJsonArr = ret.resultJsonArr;
                            var audioFlag = true;
                            for(var i=0;i<resultJsonArr.length;i++) {
                                if(resultJsonArr[i] == "") {
                                    audioFlag = false;
                                    break;
                                }
                                var retObj = JSON.parse(resultJsonArr[i]);
                                console.log(retObj['audioFlag']);
                                if(retObj['audioFlag'] == 'false' || retObj['result']=="") {
                                    audioFlag = false;
                                    break;
                                }
                            }
                            console.log(audioFlag);
                            if(audioFlag == false) {
                                $('#loading').text('引擎错误，合成失败...');
                                dlg_loading.show();
                                def.resolve();
                                setTimeout(function() {
                                    dlg_loading.hide();
                                    commands.showSelectorPop("卡片生成失败，请重新生成。",function(){
                                        commands.hidePop();
                                    },null,this,[
                                        {
                                            label: '确定',
                                            cssClass: 'btn-primary',
                                            action: function () {
                                                commands.hidePop();
                                                dlg.modal('show');
                                            }
                                        }
                                    ]);
                                },3000);

                            }else {
                                io.writeFile(matePath, JSON.stringify(metaJson));
                                io.writeIMG(thumbImagePath, data).done(function () {
                                    var rel = _self.getRelInfo();

                                    rel = {"id": s.NewRId(), "src": relDir, "title": "", "des": "", "type": "dir"};
                                    s.addRelationInfo(rel);

                                    _self.rid = rel.id;
                                    _self.setRelInfo(rel);

                                    _self.setSrc(thumbImagePath+"?"+Math.random(), function () {
                                        var mainSize = s.getCanvasSize();
                                        _self.width = 905;
                                        _self.height = 590;
                                        _self.scaleX = 1.2;
                                        _self.scaleY = 1.2;

                                        _self.left = (mainSize[0]-_self.width*_self.scaleX)*0.5;
                                        _self.top = (mainSize[1]-_self.height*_self.scaleY)*0.5;

                                        s.add(_self);

                                        s.renderAll();
                                        console.log(s.toJSON());

                                        setTimeout(function(){
                                            commands.showThumbImg(Global.CurrentSlide.c._canvas);
                                        },100);

                                        // 用户统计
                                        LM.statisticsMoudleTime('4009','trigger','situdlg_count');
                                        def.resolve();
                                        setTimeout(function () {
                                            dlg_loading.hide();
                                        }, 100);
                                    });
                                });
                            }
                        });
                    });
                }else {
                    $('#loading').text('无法联网，合成失败...');
                    dlg_loading.show();
                    def.resolve();
                    setTimeout(function() {
                        dlg_loading.hide();
                    },3000);
                }
            });
        }
        return def.promise();
    };
    fabric.Situdlg.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.Situdlg.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };

});