/**
 * Created by ythuang on 14-7-7.
 */
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 AppContext = require('share/assert/js/appcontext').AppContext;
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var flipardTemplate = require('./flipcardtemplate').flipardTemplate;
    var isUpdate = false;

    fabric.Flipcard.prototype.showEditDialog = function (opt) {
        isUpdate = false;
        var _self = this;
        if (opt) {
            isUpdate = true;
            this.id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
        }

        createDlg().done(function (dlg) {
            dlg.modal({show: true, keyboard: false, backdrop: "static"});
            dlg.on('hidden.bs.modal', function (e) {
                dlg.remove();
                Global.isEditing = false;
            });

            flipardTemplate.initDatas();
            flipardTemplate.init();

            if (opt) {
                dlg.find('#btn_yangshi').hide();
                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);
                    var s = Global.CurrentSlide.c;
                    var wdir = Path.join(s.getCurSlidePath(), 'media', _self.id);
                    for (var i = 0; i < cmd.cards.length; i++) {
                        if (cmd.cards[i].front.type == 'img') {
                            cmd.cards[i].front.value = Path.join(wdir, cmd.cards[i].front.value);
                        }
                        if (cmd.cards[i].back.type == 'img') {
                            cmd.cards[i].back.value = Path.join(wdir, cmd.cards[i].back.value);
                        }
                    }
                    flipardTemplate.setCmdText(cmd);
                    flipardTemplate.createFipCardArray();
                    flipardTemplate.createFlipCardBar();
                });
            } else {
                flipardTemplate.createFipCardArray();
                flipardTemplate.createFlipCardBar();
                flipardTemplate.showEditFlip();
            }

            // 绑定事件
            /**
             * 绑定“删除翻翻卡”按钮
             */
            dlg.find("#btn_del").click(function () {
                flipardTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    flipardTemplate.deleteFlipCard();
                });
            });

            /**
             * 绑定 “排序”按钮 到 排序页面
             */
            dlg.find('#btn_sort').bind('click', function () {
                flipardTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    flipardTemplate.showSortCard();

                    flipardTemplate.sortCard();
                    dlg.find("#btn_bar2").hide();
                    dlg.find("#btn_bar1").show();
                });
            });

            /**
             *  绑定 ”完成排序“按钮 到 编辑页面
             */
            dlg.find('#btn_sort_end').bind('click', function () {
                flipardTemplate.saveSortOrder(function (arg) {
                    flipardTemplate.showEditFlip();
                    flipardTemplate.showCardFrontBack();
                    dlg.find("#btn_bar1").hide();
                    dlg.find("#btn_bar2").show();
                });
            });

            /**
             * 绑定“生成卡片”按钮 到预览页
             */
            dlg.find("#btn_end").bind('click', function () {

                flipardTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    flipardTemplate.getFlipCardInfo(function (flipcardInfo, thumbData) {
                        var isEnble = true;
                        if (flipcardInfo) {
                            for (var i = 0; i < flipcardInfo.cards.length; i++) {
                                var frontvalue = flipcardInfo.cards[i].front.value;
                                var backvalue = flipcardInfo.cards[i].back.value;
                                if (frontvalue == null || frontvalue == '' || frontvalue == 'undefined' || backvalue == null || backvalue == '' || backvalue == 'undefined') {
                                    isEnble = false;
                                    flipardTemplate.orientateFlip(i);
                                    commands.showSelectorPop(commands.getErrorMsg(5051), function (_is) {

                                        }, null, this, [
                                        {
                                            label: '确定',
                                            cssClass: 'btn-primary',
                                            action: function () {
                                                commands.hidePop();
                                            }}
                                    ]
                                    );
                                    return;
                                }
                            }
                            if (isEnble) {
                                flipardTemplate.showPreviewCard();
                                dlg.find("#btn_bar2").hide();
                                dlg.find("#btn_bar3").show();
                                flipardTemplate.previewCard();
                            }
                        }
                    });
                });
            });


            /**
             * 绑定“上一步”按钮 到编辑翻翻卡
             */
            dlg.find('#pre_step_one').bind('click', function () {
                flipardTemplate.showEditFlip();
                dlg.find("#btn_bar3").hide();
                dlg.find("#btn_bar2").show();
            });

            /**
             * 绑定“完成”按钮
             */
            dlg.find('#btn_complete').bind('click', function () {
                flipardTemplate.getFlipCardInfo(function (flipcardInfo, thumbData) {
                    if (flipcardInfo) {
                        for (var i = 0; i < flipcardInfo.cards.length; i++) {
                            var frontvalue = flipcardInfo.cards[i].front.value;
                            var backvalue = flipcardInfo.cards[i].back.value;
                            if (frontvalue == null || backvalue == null) {
                                commands.showPop(commands.getErrorMsg(5051), 2000);
                                return;
                            }
                        }
                        _self.saveToFile(flipcardInfo, thumbData);
                    }
                    dlg.modal('hide');

                    if (!isUpdate) {
                        // 用户统计
                        LM.statisticsMoudleTime('4006', 'trigger', 'flipcard_count');
                    }

                    setTimeout(function () {
                        dlg.remove();
                        Global.isEditing = false;
                        $("body").find(".modal-backdrop.fade.in").remove();
                    }, 500);
                });
            });

            /**
             * 绑定“导入样例”按钮
             */
            dlg.find('#btn_yangshi').bind('click', function () {
                flipardTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    var flipcardTemplatePath = Path.join(AppContext.getDefaultTemplate(), 'flipcardExample');
                    IO.readFile(flipcardTemplatePath + "/meta.json").done(function (jsonStr) {
                        jsonStr = jsonStr.replace(/\n/g, '\\n');
                        var cmd = JSON.parse(jsonStr);
                        for (var i = 0; i < cmd.cards.length; i++) {
                            if (cmd.cards[i].front.type == 'img') {
                                cmd.cards[i].front.value = Path.join(flipcardTemplatePath, cmd.cards[i].front.value);
                            }
                            if (cmd.cards[i].back.type == 'img') {
                                cmd.cards[i].back.value = Path.join(flipcardTemplatePath, cmd.cards[i].back.value);
                            }
                        }
                        flipardTemplate.setCmdText(cmd);
                        flipardTemplate.createFipCardArray();
                        flipardTemplate.createFlipCardBar();
                    });
                });
            });
        });
    }

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

    /**
     * 保存meta，以及其他文件
     * @param flipcardInfo
     */
    fabric.Flipcard.prototype.saveToFile = function (flipcardInfo, thumbData) {

        var _self = this;
        var slide = Global.CurrentSlide.c;
        if (!flipcardInfo)
            return;
        var cardInfo = {fullDir: "", relDir: "", flipcardInfo: flipcardInfo, thumbData: thumbData};
        //是否是重新编辑
        if (isUpdate) {
            cardInfo.fullDir = Path.join(slide.getCurSlidePath(), 'media', _self.id);
            saveFilpcard(cardInfo, _self);
        } else {
            _self.id = slide.NewWId(_self.type);
            cardInfo.fullDir = Path.join(slide.getCurSlidePath(), 'media', _self.id);
            cardInfo.relDir = Path.join('media', _self.id);
            IO.mkdir(cardInfo.fullDir).done(function () {
                saveFilpcard(cardInfo, _self);
            });
        }
        Global.isVariety = true;
    }
    fabric.Flipcard.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.Flipcard.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };
    function saveFilpcard(cardInfo, self) {
        var slide = Global.CurrentSlide.c;
//        var self = self;
        var fullDir = cardInfo.fullDir;
        var relDir = cardInfo.relDir;
        var flipcardInfo = cardInfo.flipcardInfo;
        var thumbData = cardInfo.thumbData;
        var newFlipcardImgSrcArr = [];

        //把绝对路径替换成只留图片名称，并拷贝图片
        for (var i = 0; i < flipcardInfo.cards.length; i++) {
            if (flipcardInfo.cards[i].front.type == 'img') {
                var frontSrc = flipcardInfo.cards[i].front.value;
                var newFrontSrc = commands.randomString(5) + '.' + frontSrc.substring(frontSrc.lastIndexOf(".") + 1);
                var desFrontImgPath = Path.join(fullDir, newFrontSrc);
                if (!(desFrontImgPath === frontSrc)) {
                    IO.copyFileSync(frontSrc, desFrontImgPath);
                }
                flipcardInfo.cards[i].front.value = newFrontSrc;
                newFlipcardImgSrcArr.push(newFrontSrc);
            }
            if (flipcardInfo.cards[i].back.type == 'img') {
                var backSrc = flipcardInfo.cards[i].back.value;
                var newBackSrc = commands.randomString(5) + '.' + backSrc.substring(backSrc.lastIndexOf(".") + 1);
                var desBackImgPath = Path.join(fullDir, newBackSrc);
                if (!(desBackImgPath === backSrc)) {
                    IO.copyFileSync(backSrc, desBackImgPath);
                }
                flipcardInfo.cards[i].back.value = newBackSrc;
                newFlipcardImgSrcArr.push(newBackSrc);
            }
        }

        var fs = window.require("fs");
        fs.readdir(fullDir, function (err, fileNameArray) {
            if (err) {
                console.error(err);
            }
            for (var i = 0; i < fileNameArray.length; i++) {
                var indexFlag = $.inArray(fileNameArray[i], newFlipcardImgSrcArr);
                if (indexFlag === -1 && fileNameArray[i] !== 'meta.json') {
                    fs.unlink(Path.join(fullDir, fileNameArray[i]));
                }
            }
            var metaPath = Path.join(fullDir, 'meta.json');
            IO.writeFile(metaPath, JSON.stringify(flipcardInfo)).done(function (result) {
                if (result) {
                    //将base64转为图片
                    var thumbImgPath = Path.join(fullDir, "thumbnail.png");
                    IO.writeIMG(thumbImgPath, thumbData).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);
                        }
                        self.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                            if (!isUpdate) {
                                self.scaleX = 1.3;
                                self.scaleY = 1.3;
                                var mainSize = slide.getCanvasSize();
                                self.left = (mainSize[0] - self.width * self.scaleX) * 0.5;
                                self.top = (mainSize[1] - self.height * self.scaleY) * 0.5;
                                slide.add(self);
                            }
                            slide.renderAll();
                            commands.showThumbImg(Global.CurrentSlide.c._canvas);
                        });
                    });
                } else {
                    commands.showPop("翻翻卡保存失败，请重试。");
                }
            });
        });
    }
});