/**
 * Created by jhwang on 14-6-26.
 */
define(function (require, exports) {

    var Path = require('../../../../../share/assert/js/path');
    var IO = require('../../../../../share/assert/js/ioutil_desktop.js').IOUtil;
    var Tpl = require('../../../../../share/assert/js/template');
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var commands = require('editor/assert/js/utils/commands').commands;

    var title = "";
    var hideEquation = false;
    var eqNum = 2;

    /**
     * 保存meta，以及其他文件
     * @param result
     */
    fabric.MathGraph.prototype.saveToFile = function (result) {
        var self = this;

        var s = Global.CurrentSlide.c;
        if (!result)
            return;
        Global.isVariety = true;
        var isUpdate = true;
        if (!self.id) {
            isUpdate = false;
            self.id = s.NewWId(self.type);
            // 用户统计
            LM.statisticsMoudleTime('4002','trigger','mathgraph_count');
        }
        var relDir = Path.join('media', self.id);
        var wdir = Path.join(s.getCurSlidePath(), relDir);
        IO.mkdir(wdir).done(function () {
            var imgPath = Path.join(wdir, 'thumbnail.png');
            var metaPath = Path.join(wdir, 'meta.json');
            var metaContent = {"cardtype":"mathgraph", "title": title, "text": result.text, "image": "thumbnail.png",
                "hideEq":hideEquation, "scale":result.scale};
            IO.writeFile(metaPath, JSON.stringify(metaContent));
            IO.writeIMG(imgPath, result.img).done(function () {
                var rel = self.getRelInfo();
                if (!isUpdate) {
                    rel = {"id": s.NewRId(), "src": relDir, "des": "", "type": "dir"};
                    s.addRelationInfo(rel);

                    self.rid = rel.id;
                    self.setRelInfo(rel);
                }

                self.setSrc(imgPath+"?"+commands.randomString(5), function () {
                    if (!isUpdate) {
                        var pos = getRightPostion(s.getCanvasSize(), result.size);
                        self.left = pos[0];
                        self.top = pos[1];
                        s.add(self);
                    }

                    s.renderAll();
                    setTimeout(function(){
                        commands.showThumbImg(Global.CurrentSlide.c._canvas);
                    },50)

//                    console.log(s.toJSON());
                });

            })
        });

    }

    function getRightPostion(canvasSize, eleSize) {
        var x = (canvasSize[0] - eleSize[0]) / 2;
        var y = (canvasSize[1] - eleSize[1]) / 2;
        return [x, y];
    }

    function createDlg() {
        if ($('#modal-content'))    $('#modal-content').remove();
        var def = jQuery.Deferred();
        seajs.use('editor/assert/js/widget/mathgraph/edit.tpl', function (tpl) {
                var dlg = $(tpl);
                $('body').append(dlg);
                var top = (window.innerHeight - 700) / 2;
                dlg.css("paddingTop", top);
                def.resolve(dlg);
            }
        );
        return def.promise();
    }

    function setTitle(titleStr){
        if(titleStr!=undefined){
            $("#titleBox").val(titleStr);
            title = titleStr;
        }
        else{
            title = "";
        }
    }

    function setCheckBox(hideEq){
        if(hideEq === true){
            hideEquation = true;
            $("#checkBox").attr("checked","checked");
        }
        else{
            hideEquation = false;
            $("#checkBox").removeAttr("checked");
        }
    }

    function setScale(scale){
        if(scale != undefined){
            $("#graphFrm")[0].contentWindow.setScale(scale);
        }
    }

    //计算标题整体字符所占长度
    function calcStrLength(str){
        var len = 0;
        //最多实际能放下的“当前”字符串的长度位置
        var mostIndex = 0;
        for (var i = 0; i < str.length; i++) {
            var char = str.charCodeAt(i);
            //单字节加1
            if ((char >= 0x0001 && char <= 0x007e) || (0xff60 <= char && char <= 0xff9f)) {
                len++;
            }
            else {
                len += 1.7;
            }
            if(len<50){
                mostIndex = i;
            }
        }
        return [len,mostIndex];
    }

    function trimPrefix(latex) {
        latex = latex.replace(/f\\left\(x\\right\)=/g, "");
        latex = latex.replace(/ƒ\(x\)=/g, "");
        while(latex.indexOf("=") == 0){     //替换开头出现的=号
            latex = latex.replace("=", "");
        }
        return latex;
    }

    /**
     * 图片合成
     * */
    function mergeImg(bgImg, foreImg, callback) {
        var canvas = document.getElementById("outputCanvas");
        var ctx = canvas.getContext("2d");
        var img = new Image();
        img.src = bgImg;
        img.onload = function () {
            var img2 = new Image();
            img2.src = foreImg;
            img2.onload = function () {
                canvas.width = img2.naturalWidth;
                canvas.height = img.naturalHeight + img2.naturalHeight;

                ctx.drawImage(img, 0, 0);
                var x = 0;
                var y = img.naturalHeight;
                ctx.drawImage(img2, x, y);

                if (callback) {
                    callback(canvas.toDataURL("image/png"), [canvas.width, canvas.height]);
                }
            }
        }
    }

    /**
     * 用于解决根号显示异常的问题
     * */
    function fixSqrtProblem() {
        setTimeout(function () {
            $('.sqrt-prefix').each(function () {
                $(this).css('-webkit-transform', "scale(1,0.9)");
            });
        }, 500);
    }

    /**
     * 初始化公式框
     * */
    function initInputBox(obj,latex){
        obj.mathquill('editable').mathquill('redraw').mathquill("latex",latex);
        $(obj.find("textarea")[0]).css("background-color","transparent").css("resize","none");     //将textarea的背景设为透明，解决其生成的图片中有白色背景的问题
        obj.find("textarea")[0].addEventListener("input",function(e){
            if(e.target.value){
                e.target.value = e.target.value.replace(/\s+/g, "");
                e.target.value = e.target.value.replace(/[\u4e00-\u9fa5]/g,'');
            }
        },false) ;
    }

    function appendLatex(obj,mq) {
        var ele = $(mq);
        var latex = ele.mathquill('latex');
        obj.mathquill('write', latex);
    }

    /**
     * 修改公式框状态，用于生成图片
     * */
    function changeInputBox(obj){
        obj.css("border", "0px");
        obj.find("textarea")[0].style.border = "0px";
        obj.removeClass("mathquill-editable");
        obj.addClass("mathquill-embedded-latex");
    }

    /**
     * 公式编辑界面
     * */
    function initView(){
        $("#inputView").css("display","block");
        $("#btnPlot").css("display","block");

        $("#drawView").css("display","none");
        $("#preStep").css("display","none");
        $("#btnPrimary").css("display","none");
    }

    /**
     * 图像绘制界面
     * */
    function showDrawView(){
        $("#inputView").css("display","none");
        $("#btnPlot").css("display","none");

        $("#drawView").css("display","block");
        $("#preStep").css("display","block");
        $("#btnPrimary").css("display","block");
    }

    /**
     * 绘制错误信息
     * */
    function showMessage(obj,message){
        commands.showSelectorPop(message,function(_is){

            },null,this,[{
            label: '确定',
            cssClass: 'btn-primary',
            action: function(){
                commands.hidePop();
                obj.mathquill("latex", "y=");
            }}]
        );
    }

    /**
     * 显示编辑框
     * @param opt
     */
    fabric.MathGraph.prototype.showEditDialog = function (opt) {
        var self = this;
        Global.isEditing = true;
            createDlg().done(function (dlg) {
                seajs.use('editor/assert/js/3rdparty/mathquill/mathquill.min.js', function () {
                    initView();
                    var frmWin = $('#graphFrm')[0].contentWindow;

                    $('#inputMath').bind("click",function(){
                        currentInputer = $(this);
                    });
                    var inputClone = $("#inputMath").clone(true).removeAttr("id");
                    initInputBox($("#inputMath"),"y=");     //先clone再分别初始化，防止选中时卡死
                    var currentInputer = $("#inputMath");

                    var showClone = $("#eq1").clone(true).removeAttr("id");
                    initInputBox($("#eq1"),"");

                    $("#addInputBox").bind("click",function(){
                        var newInputBox = inputClone.clone(true);
                        initInputBox(newInputBox,"y=");
                        $("#editDiv").append(newInputBox);
                        currentInputer = newInputBox;
                        $("#addInputBox").css("display","none");
                    });

                    /**
                     * 获取编辑框的公式
                     * */
                    function getAllLatex(){
                        var allLatex = "";
                        var len = $("#editDiv").children().length;
                        if(len > eqNum)     //两个公式，
                            len = eqNum;
                        for(var i=0;i<len;i++)
                        {
                            var latex = trimPrefix($($("#editDiv").children()[i]).mathquill('latex'));
                            if(latex !=="" && latex != "y="){
                                if(latex.indexOf("y=") < 0 && latex.indexOf("=") < 0 && latex.indexOf("f(x)=") < 0){
                                    latex = "y=" + latex;
                                }
                                if(allLatex){
                                    allLatex = allLatex+","+latex;
                                }
                                else{
                                    allLatex = latex;
                                }
                            }
                        }
                        return allLatex;
                    }

                    /**
                     * 设置编辑框的公式
                     * */
                    function setAllLatex(allLatex){
                        if(!allLatex){
                            return;
                        }
                        var latexs = allLatex.split(",",eqNum);
                        for(var i=0;i<latexs.length;i++)
                        {
                            if(i>0 && $($("#editDiv").children()[i]).length==0)
                            {
                                var newInputBox = inputClone.clone(true);
                                $("#editDiv").append(newInputBox);
                                initInputBox(newInputBox,"y=");
                                $("#addInputBox").css("display","none");
                            }
                            if(latexs[i])
                            {
                                while(latexs[i].indexOf("=") == 0){     //删除开头出现的=号
                                    latexs[i] = latexs[i].replace("=", "");
                                }
                                if(latexs[i].indexOf("=") < 0 && latexs[i].indexOf("y=") < 0 && latexs[i].indexOf("f(x)=")){
                                    latexs[i] = "y=" + latexs[i];
                                }
                                $($("#editDiv").children()[i]).mathquill("latex",latexs[i]);
                            }
                        }
                    }

                    /**
                     * 设置用于显示的公式（编辑框的截图错误，无法直接使用）
                     * */
                    function setEqDiv(cmd){
                        if(!cmd)    return;

                        for(var i = 1; i< $("#eqDiv").children().length; i++){       //只保留第一个
                                $($("#eqDiv").children()[i]).remove();
                        }

                        var latexs = cmd.split(",",eqNum);
                        for(var i=0;i<latexs.length;i++){
                            if($($("#eqDiv").children()[i]).length==0){   //若编辑框对应的公式框不存在
                                var newClone = showClone;
                                $("#eqDiv").append(newClone);
                                initInputBox($($("#eqDiv").children()[i]),"");
                            }
                            else{
                                $($("#eqDiv").children()[i]).mathquill('write','');//设为空，防止第二次设置时截图出现乱码
                            }
                            if(latexs[i]){
                                while(latexs[i].indexOf("=") == 0){     //删除开头出现的=号
                                    latexs[i] = latexs[i].replace("=", "");
                                }
                                if(latexs[i].indexOf("=") < 0 && latexs[i].indexOf("y=") < 0 && latexs[i].indexOf("f(x)=")){
                                    latexs[i] = "y=" + latexs[i];
                                }
                                $($("#eqDiv").children()[i]).mathquill("latex",latexs[i]);
                            }
                        }
                        for(var i=0;i<$("#eqDiv").children().length;i++)
                        {        //公式填充完毕后转换为非编辑状态
                            changeInputBox($($("#eqDiv").children()[i]));
                        }
                        fixSqrtProblem();
                        $("#eqDiv").css("border", "0px");
                    }

                    $("#titleBox").bind("input propertychange",function(){
                        var titleLengthArr= calcStrLength(this.value);
                        var titleStrLength = titleLengthArr[0];
                        var mostIndex = titleLengthArr[1];
                        if (titleStrLength>50) {     //标题过长，截断处理
                            $("#titleBox").val($("#titleBox").val().substr(0, mostIndex+1));
                        }
                        title = $("#titleBox").val();
                    });

                    $("#sampleEqulal").on("click", "li", function () {
                        for(var i=0;i<$("#sampleEqulal").children().length;i++){
                            $($("#sampleEqulal").children()[i]).removeClass("fu_active");
                        }
                        $(this).addClass("fu_active");
                        appendLatex(currentInputer,$(this).find("span")[0]);
                    });

                    $('#sampleEqulal li>span').each(function () {
                        $(this).mathquill().mathquill('redraw');
                    });

                    $('#btnPlot').bind('click', function () {
                        var cmd = getAllLatex();
                        if(!cmd)    return;
                        if(!plotLatex(cmd)) return;
                        setEqDiv(cmd);
                        showDrawView();
                    });

                    $("#preStep").bind("click",function(){
                        initView();
                    });

                    $('#btnZoomIn').bind('click', function () {
                        frmWin.zoomIn();
                    });

                    $('#btnZoomOut').bind('click', function () {
                        frmWin.zoomOut();
                    });

                    $("#checkBox").bind("click",function(){
                        if($("#checkBox").attr("checked")===undefined){
                            hideEquation = true;
                            $("#checkBox").attr("checked","checked");
                        }
                        else{
                            hideEquation = false;
                            $("#checkBox").removeAttr("checked");
                        }
                    });

                    $("#btnPrimary").bind('click', function () {
                        var cmd = getAllLatex();
                        if(!cmd)    return;
                        setEqDiv(cmd);//重新设置显示公式，防止出现阴影

                        var result = $('#graphFrm')[0].contentWindow.getResult();
                        result.text = cmd;

                        if(hideEquation){//隐藏公式
                            if(!title){//标题为空时
                                var canvas = document.getElementById("outputCanvas");
                                var img = new Image();
                                img.src = result.img;
                                img.onload = function () {
                                    canvas.width = img.naturalWidth;
                                    canvas.height = img.naturalHeight;
                                    result.size = [canvas.width,canvas.height];
                                    self.saveToFile(result);
                                    dlg.modal('hide');
                                }
                            }
                            else{//标题不为空
                                $("#titleBox").remove();
                                $("#titleDiv").html(title).css("height", "43px").css("border", "0px");
                                html2canvas($("#titleDiv")[0],{
                                    onrendered: function(canvas){
                                        var titleData = canvas.toDataURL("image/png");
                                        mergeImg(titleData,result.img,function(data,sizeArr){
                                            result.img = data;
                                            result.size = sizeArr;

                                            self.saveToFile(result);
                                        });
                                        dlg.modal('hide');
                                    }
                                });
                            }
                        }
                        else{//不隐藏公式
                            html2canvas($("#eqDiv")[0],{
                                onrendered: function(canvas){
                                    var eqData = canvas.toDataURL("image/png");
                                    mergeImg(result.img,eqData,function(graphData,sizeArr){
                                        if(!title){
                                            result.img = graphData;
                                            result.size = sizeArr;
                                            self.saveToFile(result);
                                            dlg.modal('hide');
                                        }
                                        else{//标题不为空
                                            $("#titleBox").remove();
                                            $("#titleDiv").html(title).css("height", "43px").css("border", "0px");
                                            html2canvas($("#titleDiv")[0],{
                                                onrendered: function(canvas){
                                                    var titleData = canvas.toDataURL("image/png");
                                                    mergeImg(titleData, graphData,function(data,sizeArr){
                                                        result.img = data;
                                                        result.size = sizeArr;
                                                        self.saveToFile(result);
                                                    });
                                                    dlg.modal('hide');
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });

                    function plotLatex(cmds){
                        var isSucceed = false;
                        if(cmds){
                            isSucceed = true;
                            try{
                                    frmWin.setCmdsText(cmds);
                            }
                            catch(e){
                                showMessage($($("#editDiv").children()[e]),"公式"+(e+1)+"无法绘制图像，请修改后再绘制");
                                currentInputer = $($("#editDiv").children()[e]);
                                isSucceed = false;
                            }
                        }
                        return isSucceed;
                    }

                    var iframe = document.getElementById("graphFrm");
                    if (iframe.attachEvent) {
                        iframe.attachEvent("onload", setCmd);
                    }
                    else {
                        iframe.onload = setCmd;
                    }

                    function setCmd() {
                        title = "";
                        hideEquation = false;
                        if (opt) {
                            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 (content) {
                                setAllLatex(JSON.parse(content).text);
                                setTitle(JSON.parse(content).title);
                                setCheckBox(JSON.parse(content).hideEq);
//                                setZoomTime(JSON.parse(content).zmTime);
                                setScale(JSON.parse(content).scale);
                            });
                        }
                    }

                    fixSqrtProblem();

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

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

                });
            });
    };
    fabric.MathGraph.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.MathGraph.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };
});