/**
 * Created with JetBrains WebStorm.
 * User: Administrator
 * Date: 14-7-7
 * Time: 下午3:20
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {

    var Path = require('../../../../../share/assert/js/path');
    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;

    require("../../3rdparty/mathquill/mathquill.min.js");

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

        var slide = Global.CurrentSlide.c;
        if (!result)    return;
        var isUpdate = true;
        if (!self.id) {
            isUpdate = false;
            self.id = slide.NewWId(self.type);
        }
        var relDir = Path.join('media', self.id);
        var wdir = Path.join(slide.getCurSlidePath(), relDir);
        IO.mkdir(wdir).done(function () {
            var imgPath = Path.join(wdir, 'thumbnail.png');
            var metaPath = Path.join(wdir, 'meta.json');
            var metaContent = {'cardtype':'mathequation','cmd': result.text, 'image': 'thumbnail.png'};
            IO.writeFile(metaPath, JSON.stringify(metaContent));
            IO.writeIMG(imgPath, result.img).done(function () {
                var rel = self.getRelInfo();
                if (!isUpdate) {
                    rel = {"id": slide.NewRId(), "src": relDir, "title": "", "des": "", "type": "dir"};
                    slide.addRelationInfo(rel);

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

                    // 用户统计
                    LM.statisticsMoudleTime('4003','trigger','mathequation_count');
                }

                self.setSrc(imgPath+"?"+commands.randomString(5), function () {
                    if (!isUpdate) {
                        self.left=200;
                        self.top=100;
                        slide.add(self);
                    }

                    slide.renderAll();

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

            })
        });

    }


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

        var def = jQuery.Deferred();
        seajs.use('editor/assert/js/widget/mathequation/edit.tpl', function (tpl) {
                var dlg = $(tpl);
                $('body').append(dlg);
                var top = (window.innerHeight - 600) / 2;
                dlg.css("paddingTop", top);
                def.resolve(dlg);
            }
        );

        return def.promise();
    }


    /**
     * 显示编辑框
     * @param opt
     */
    fabric.MathEquation.prototype.showEditDialog = function (opt) {
        var self = this;
        Global.isEditing = true;
        Global.isVariety = true;
        createDlg().done(function (dlg) {
            var jmeMath = [
                [
                    "{/}frac{}{}", "^{}/_{}", "x^{}", "x_{}", "x^{}_{}", "{/}bar{}", "{/}sqrt{}", "{/}nthroot{}{}",
                    "{/}sum_{a}^{b}{c}", "{/}sum", "{/}log_{}", "{/}ln", "{/}int_{}^{}", "{/}oint_{}^{}"
                ],
                [
                    "{/}alpha", "{/}beta", "{/}gamma", "{/}delta", "{/}varepsilon", "{/}varphi", "{/}lambda", "{/}mu",
                    "{/}rho", "{/}sigma", "{/}omega", "{/}Gamma", "{/}Delta", "{/}Theta", "{/}Lambda", "{/}Xi",
                    "{/}Pi", "{/}Sigma", "{/}Upsilon", "{/}Phi", "{/}Psi", "{/}Omega"
                ],
                [
                    "+", "-", "{/}pm", "{/}times", "{/}ast", "{/}div", "/", "{/}bigtriangleup",
                    "=", "{/}ne", "{/}approx", ">", "<", "{/}ge", "{/}le", "{/}infty",
                    "{/}cap", "{/}cup", "{/}because", "{/}therefore", "{/}subset", "{/}supset", "{/}subseteq", "{/}supseteq",
                    "{/}nsubseteq", "{/}nsupseteq", "{/}in", "{/}ni", "{/}notin", "{/}mapsto", "{/}leftarrow", "{/}rightarrow",
                    "{/}Leftarrow", "{/}Rightarrow", "{/}leftrightarrow", "{/}Leftrightarrow"
                ],
                [
                    "(x-1)(x+3)","{/}sqrt{a^2+b^2}"
                ],
                [
                    "H_2+CuO===Cu+H_2O",
                    "Zn+H_2SO_4===ZnSO_4+H_2{/}uparrow",
                    "CuO+2HCl===CuCl_2+H_2O",
                    "HCl+NaOH===NaCl+H_2O"
                ],
                [
                    "W=UIt=I^2Rt={/}frac{U^2}{R}t",
                    "F_1L_1=F_2L_2",
                    "v={/}frac{s}{t}"
                ]
            ];

            function insert(q) {
                $("#jme-math").focus().mathquill("write", q.replace("{/}", "\\"));
            }

            function mathHtml(obj) {
//    var cols = 8;//一行放几个
                var slidLen = 34;//每个图标的宽或高
                var html = "<div class='mathIcon'>";
                for (var i = 0; i < obj.count; i++) {
                    html += "<li onclick=\"$('#jme-math').focus().mathquill('write','" + jmeMath[obj.groupid][i] + "'.replace('{/}', '\\\\'))\" style=\"float:left;list-style:none;background-position:-" +
                        (obj.x + Math.floor(i % 8) * slidLen) + "px -" + (obj.y + Math.floor(i / 8) * slidLen) + "px;\"></li>";
                }
                html += "</div>";
//    if (obj.count > cols * 2) {
//        html += "<div class='more' mrows='" + Math.floor((obj.count + cols - 1) / cols) + "' isOpen='0'>更多</div>"
//    }
                return html;
            }

            function mathHtml2(obj){
                var html = "<div class='mathIcon'>";
                for (var i = 0; i < obj.count; i++) {
                    html += "<div onclick=\"$('#jme-math').focus().mathquill('write','" + jmeMath[obj.groupid][i] + "'.replace('{/}', '\\\\'))\" style=\"float:left;width:100%;margin:5px\">" +
                        "<div style='float:left;border:1px solid #CCCCCC;padding:5px'><img src=\"./editor/assert/images/"+obj.prefix+i+".gif\" /></div></div>";
                }
                html += "</div>";
                return html;
            }


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

            function setCmdText(cmd) {
                $("#jme-math").mathquill('latex', cmd);
                fixSqrtProblem();
            }

            /**
             * 将canvas中的白色像素改为透明
             * */
            function transparent(canvas) {
                var ctx = canvas.getContext("2d");
//        ctx.imageSmoothingEnabled = false;
//        ctx.webkitImageSmoothingEnabled = false;
//        ctx.mozImageSmoothingEnabled = false;
                var image = ctx.getImageData(0, 0, canvas.width, canvas.height);
                var imageData = image.data;
                var transparentColor = {r: 0, g: 0, b: 0, a: 0};

                for (var i = 0, n = imageData.length; i < n; i += 4) {
                    var r = imageData[i],
                        g = imageData[i + 1],
                        b = imageData[i + 2],
                        a = imageData[i + 3];

                    if(r > 200 && g > 200 && b > 200){  //修改像素点的rgba值
                        imageData[i] = transparentColor.r;
                        imageData[i + 1] = transparentColor.g;
                        imageData[i + 2] = transparentColor.b;
                        imageData[i + 3] = transparentColor.a;
                    }
                }
// and put the imagedata back to the canvas
                ctx.putImageData(image, 0, 0);
            }

            function getResult(callback) {
                var latex = $("#jme-math").mathquill('latex');
                if(latex == "") return;
                //将公式内容重新填装一次，避免选中公式造成的图片阴影,目前未找到别的解决办法
                $("#jme-math").mathquill('write','').mathquill('latex', latex);

                $("#jme-math").css("border", "0px");
                $("#jme-math").find("textarea")[0].style.border = "0px";
                $("#jme-math").removeClass("mathquill-editable");
                $("#jme-math").addClass("mathquill-embedded-latex");
                $("#jme-math").width('');

                html2canvas($("#mathDiv")[0], {
                    onrendered: function (canvas) {
                        $("#jme-math").css("border", "1px solid #C5C5C5");
                        $("#jme-math").find(".textarea")[0].style.border = "1px";
                        $("#jme-math").width('518px');
                        $("#jme-math").removeClass("mathquill-embedded-latex");
                        $("#jme-math").addClass("mathquill-editable");
                        transparent(canvas);
                        var result = null;
                        var cmd = $("#jme-math").mathquill('latex');
                        if (cmd) {
                            result = {"img": canvas.toDataURL(), "text": cmd};
                        }
                        if (callback) {
                            callback(result);
                        }
                    }
                });
            }

            function jmeInit() {
                //隐藏内容div
                $(".tabContent div.mathBox").hide();
                //菜单点击事件
                $(".tabTitle li").click(function () {
                    $(".tabContent div.mathBox").hide();
                    var n = 0;
                    var obj = this;
                    $(".tabTitle li").each(function (i, o) {
                        if (obj == o) {
                            n = i;
                        }
                    });
                    $(".tabTitle li").removeClass("current");
                    $(obj).addClass("current");
                    $(".tabContent div.mathBox:eq(" + n + ")").show();
                });
                //缺省显示第一个
                $(".tabTitle li:eq(0)").click();
                //公式定义
                $(".tabContent div.mathBox:eq(0)").html(mathHtml({
                    groupid: 0,
                    x: 0,
                    y: 272,
                    count: 14
                }));
                $(".tabContent div.mathBox:eq(1)").html(mathHtml({
                    groupid: 1,
                    x: 0,
                    y: 170,
                    count: 22
                }));

                $(".tabContent div.mathBox:eq(2)").html(mathHtml({
                    groupid: 2,
                    x: 0,
                    y: 0,
                    count: 36
                }));

                $(".tabContent div.mathBox:eq(3)").html(mathHtml2({
                    groupid: 3,
                    prefix:'ds',
                    count: 2
                }));

                $(".tabContent div.mathBox:eq(4)").html(mathHtml2({
                    groupid: 4,
                    prefix:'hx',
                    count: 4
                }));

                $(".tabContent div.mathBox:eq(5)").html(mathHtml2({
                    groupid: 5,
                    prefix:'wl',
                    count: 3
                }));

//    //常用公式,更多按钮绑定的事件
//    $(".tabContent div.mathBox div.more").click(function () {
//        var rowHei = 40;
//        var mi = $(this).parent().find(".mathIcon");
//        if ($(this).attr("isOpen") == '0') {
//            mi.animate({"height": (rowHei * Number($(this).attr("mrows"))) + "px"});
//            $(this).html("↑ 收起");
//            $(this).attr("isOpen", '1');
//        } else {
//            mi.animate({"height": (rowHei * 2) + "px"});
//            $(this).html("更多");
//            $(this).attr("isOpen", '0');
//        }
//    });

                //公式编辑框
                $("#jme-math").html("").mathquill('editable').mathquill('write', "");
                $($("#jme-math").find("textarea")[0]).css("background-color","transparent");     //将textarea的背景设为透明，解决其生成的图片中有白色背景的问题

                $("#jme-math").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) ;

//                var isSelecting = false;
//                $("#jme-math").mousedown(function(){
//                    isSelecting = true;
//                });
//
//                $("body").mouseleave(function(){
////        console.log("mouseleave");
//                    if(isSelecting){
////            console.log("isSelecting");
//                        $("body").mouseup();
//                        isSelecting = false;
//                    }
//                });
            }

            jmeInit();

            $("#btnPrimary").bind('click', function () {
                getResult(function (result) {
                    if (result) {
                        self.saveToFile(result);
                    }
                    dlg.modal('hide');
                });
            });

            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) {
                    var cmd = JSON.parse(content).cmd;
                    setCmdText(cmd);
                });
            }

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

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


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