/**
 * Created by W.J.Chang on 2014/7/15.
 */
define(function(require,exports,modules){
    var path = require('../../../../../share/assert/js/path');
    var urlCheck = require('editor/assert/js/addon/urlCheck');

    var tts = require('editor/assert/js/addon/msptts');
    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 dlg = null;
    var dlg_loading = null;

    seajs.use('./share/assert/style/pop/css/pop.css');
    seajs.use('./editor/assert/style/speechapp/speech.css');
    seajs.use('./editor/assert/style/speechapp/speech_font.css');
    seajs.use('./editor/assert/js/3rdparty/html2canvas.js');
    seajs.use('./editor/assert/js/utils/fileSystemUtil.js');

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

        console.log('eneval 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: 600px;height: 500px;">' +


            '<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="padding: 0;">' +
            '<div id="evaluationTmpPanel" class="gallery_box ui-draggable" hidden="false" style="display: block;padding-top: 0;">' +
            '<div id="canvas_node" style="background-color: #ffffff">' +
            '<div id="evaluationTab" class="tab_c" lang="x" >字词发音评测</div>' +
            '<div id="evaluationTabContent" class="tab_b" lang="x">请在下面文本框内输入需要评测的英文单词</div>' +
            '<div id="evaluationEditPanel" style="display: block;">' +
            '<div id="evaluationText" class="pc_textarea"><textarea id="evaluationDescription" name="" cols="" rows=""></textarea></div>' +
            '<div id="evaluationTips" class="pc_tips" lang="x">温馨提示：如果输入多个单词，请用逗号‘，’或用空格进行分隔<br/>例如：apple peer sheep</div>' +
            '</div>' +

            // 预览第二套 UI
            '<div class="scene2" id="previewPanel" style="display: none;background-color: #ffffff;">'+
            '    <div class="scene_cont">'+
            '        <ul class="scene_cont_c clearfix" id="pre_list">'+
            '        </ul>'+
            '    </div>'+
            '    <div class="scene_func clearfix">'+
            '        <span class="voice"><img src="editor/assert/images/speechapp/voice.png" alt=""></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 class="gallery_bot temp_btn">' +
                '<a id="nextBtn" href="javascript:;" class="pop_btn fr mrmt " style="margin-top: 10px;"><span class="pop_btn_s2">下一步</span></a>' +
                '<a id="createCardBtn" href="javascript:;" class="pop_btn fr mrmt " style="display: none; margin-top: 10px;"><span class="pop_btn_s2">完成</span></a>' +
                '<a id="modifyBtn" href="javascript:;" class="pop_btn mrmt " style="display: none;float: left;margin-top: 10px;"><span class="pop_btn_s2">上一步</span></a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>');

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

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

        dlg.find("#nextBtn").bind('click', function () {
            var text = $('#evaluationDescription').val();

            text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, '');
            text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');//去除字符串中的左右空格

            if(text.length == 0) {
                $('#evaluationTips').html('请输入英文字、词，再点击下一步。');
                return;
            }

            if(text.length >100) {
                return;
            }

            $('#loading').text('正在检查网络连接...');
            dlg_loading.show();
            urlCheck.pingBaidu().done(function(ret) {
                console.log("isOnline:"+ret);
                isOnline = ret;
                if(!ret) {
                    $('#evaluationTips').text('需要联网！');
                } else {
                    gotoNext();
                }

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

        // 进行下一步
        function gotoNext() {
            var text = $('#evaluationDescription').val();

            text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, '');
            text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');//去除字符串中的左右空格

            if(text.length == 0) {
                $('#evaluationTips').html('请输入英文字、词，再点击下一步。');
                return;
            }

            if(text.length >100) {
                return;
            }

            $('#evaluationTabContent').text('');
            $('#evaluationText').hide();
            $('#evaluationTips').hide();
            $('#previewPanel').show();

            $('#pre_list').empty();
            text.split(/[\s,\uff0c]+/).forEach(function(ret) {
                var _li = '<li>'+
                    '<div class="scene_cont_ct">'+
                    '<p class="txt_top">'+ret+'</p>'+
                    '<p></p>'+
                    '</div>'+
                    '</li>';
                $('#pre_list').append(_li);
            });

            $('#nextBtn').hide();
            $('#modifyBtn').show();
            $('#createCardBtn').show();
        }

        dlg.find("#modifyBtn").bind('click', function () {
            $('#evaluationTabContent').text('1、请在下面文本框内输入需要评测的英文单词');
            $('#evaluationText').show();
            $('#evaluationTips').show();
            $('#previewPanel').hide();

            $('#nextBtn').show();
            $('#modifyBtn').hide();
            $('#createCardBtn').hide();
        });

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

        dlg.find("#evaluationDescription").bind('keyup', function () {
            var text = $('#evaluationDescription').val();

            text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, '');
            text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');//去除字符串中的左右空格

            if(text.length>0 && text.length <=100) {
                $('#evaluationTips').html('温馨提示：如果输入多个单词，请用逗号‘，’或用空格进行分隔<br/>例如：apple peer sheep');
            } else if(text.length >100) {
                $('#evaluationTips').text('温馨提示：输入的字符总数不能超过100个!');
            } else {

            }
        });

        dlg.find("#createCardBtn").bind('click', function () {

            $('#loading').text("正在生成卡片，请稍候...");
            dlg_loading.show();
            html2canvas($('#previewPanel'),{
                onrendered:function(canvas) {
                    var data = canvas.toDataURL();
                    _self.saveToFile(opt,data);

                    dlg.modal('hide');
                }
            });
        });

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

        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);
                    var wordsStr = "";

                    for(var i=0;i<metaObj.words.length;i++) {
                        wordsStr += metaObj.words[i].word + " "
                    }

                    wordsStr = wordsStr.substring(0,wordsStr.length-1);

                    $('#evaluationDescription').val(wordsStr);
                });
            } catch (e) {
                console.log("重新读取meta.json文件异常:"+e);
            }
        }

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

    };

    fabric.EnEval.prototype.saveToFile = function(opt,data) {
        var _self = this;

        var s = Global.CurrentSlide.c;

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

                    var text = $('#evaluationDescription').val();

                    text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, '');
                    text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');//去除字符串中的左右空格

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

                    var wavArr = text.split(/[\s,\uff0c]+/); //处理单词间存在逗号和空格的情况

                    console.log(wavArr);

                    var metaJson = {"cardtype":"en_word","thumbnial":"thumbnail.png","title": "","keywords": "test","words":[]};
                    for(var i=0;i<wavArr.length;i++) {
                        var tempObj = {"word":wavArr[i],"audio":"en_"+i+".mp3"};
                        metaJson.words.push(tempObj);
                    }

                    // 合成语音
                    tts.textToSpeechWithTryTimes(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();
                            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 = 765;
                                    _self.height = 540;

                                    s.renderAll();
                                    console.log(s.toJSON());
                                    setTimeout(function(){
                                        commands.showThumbImg(Global.CurrentSlide.c._canvas);
                                    },100);
                                    dlg_loading.hide();
                                });
                            });
                        }
                    });
                } else {
                    $('#loading').text('无法合成，需要联网...');
                    dlg_loading.show();
                    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);
                    var relDir = path.join('media',_self.id);
                    //FileSystemUtil.deleteFiles(wdir,['.wav','.mp3']);
                    console.log(wdir);

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

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

                        var text = $('#evaluationDescription').val();

                        text = text.replace(/[^a-zA-Z'\s,\uff0c]/g, '');
                        text = text.replace(/^[,\s\uff0c]+|[,\s\uff0c]+$/g, '');//去除字符串中的左右空格
                        var speecher = 'mary';
                        var audioPath = wdir;

                        var wavArr = text.split(/[\s,\uff0c]+/); //处理单词间存在逗号和空格的情况

                        console.log(wavArr);

                        var metaJson = {"cardtype":"en_word","thumbnial":"thumbnail.png","title": "","keywords": "test","words":[]};
                        for(var i=0;i<wavArr.length;i++) {
                            var tempObj = {"word":wavArr[i],"audio":"en_"+i+".mp3"};
                            metaJson.words.push(tempObj);
                        }

                        // 合成语音
                        tts.textToSpeechWithTryTimes(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();
                                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 = 765;
                                        _self.height = 540;
                                        _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);
                                        dlg_loading.hide();

                                        // 用户统计
                                        LM.statisticsMoudleTime('4008','trigger','eneval_count');
                                    });
                                });
                            }
                        });

                    });
                } else {
                    $('#loading').text('无法合成，需要联网...');
                    dlg_loading.show();
                    setTimeout(function() {
                        dlg_loading.hide();
                    },3000);
                }
            });


        }
    };

    fabric.EnEval.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };

    fabric.EnEval.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };

});