/**
 * 画廊编辑模块
 * Date: 2014/06/30
 * Author: luxing@iflytek.com
 * @version 1.0
 * @module gallery.edit
 */
define(function (require, exports) {
    var Path = require('../../../../../share/assert/js/path');
    var IOUtil = 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 galleryCardTemplate = require('./gallerycardtemplate').galleryCardTemplate;
    window.COMMANDS = commands;
    var isUpdate = false;

    fabric.Gallery.prototype.showEditDialog = function (opt, finishcallback) {
        isUpdate = false;
        if (opt) {
            isUpdate = true;
            opt.src = opt.src.replace(/.*?sco\//ig, '');
            this.id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
        }
        var _self = this;
        createDlg().done(function (dlg) {

            galleryCardTemplate.init();

            /**
             * 关闭按钮
             * 或使用modal('hide')关闭弹框时的回调
             */
            dlg.on('hidden.bs.modal', function (e) {
                Global.isEditing = false;
            });

            if (isUpdate) {
                var slidePath = Global.CurrentSlide.c.getCurSlidePath();
                var galleryPath = Path.join(slidePath, opt.src);
                var metaPath = Path.join(galleryPath, "meta.json");
                IOUtil.readFile(metaPath).done(function (jsonStr) {
                    var jsonObj = JSON.parse(jsonStr);
                    var images = jsonObj.images;
                    for (var i = 0; i < images.length; i++) {
                        jsonObj.images[i].src = Path.join(galleryPath, jsonObj.images[i].src);
                    }
                    galleryCardTemplate.loadGallery(jsonObj);
                });
            }
            ;
            /**
             * 编辑完成
             */
            $("#btnFinish").click(function () {
                galleryCardTemplate.getGalleryInfo(function (galleryInfo, thumbData) {
                    //Global.isEditing = false;
                    if (galleryInfo) {
                        //console.log(galleryInfo,thumbData);
                        _self.saveToFile(galleryInfo, thumbData);
                    }
                    dlg.modal('hide');

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

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

            $("#btnAddImg").click(function () {
                galleryCardTemplate.selectGalleryImg();
            });

            $("#btnDeleteCurImg").click(function () {
                galleryCardTemplate.deleteGalleryImg();
            });

            $("#btnSortComplete").click(function () {
                galleryCardTemplate.imgSortComplete();
                $("#btnAddImg").show();
                $("#btnDeleteCurImg").show();
                $("#btnImgSort").show();
                $("#btnFinish").show();
                $("#btnSortComplete").hide();
            });

            $("#btnImgSort").click(function () {
                $("#btnAddImg").hide();
                $("#btnDeleteCurImg").hide();
                $("#btnImgSort").hide();
                $("#btnFinish").hide();
                galleryCardTemplate.imgSort();
                $("#btnSortComplete").show();
            });

            $("#btnDeleteCurImg").hide();
            $("#btnImgSort").hide();
            $("#btnFinish").hide();
            dlg.modal({show: true, keyboard: false, backdrop: "static"});
        });
    }

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

    /**
     * 保存meta，以及其他文件
     * @param galleryInfo
     */
    fabric.Gallery.prototype.saveToFile = function (galleryInfo, thumbData) {
        var _self = this;
        var slide = Global.CurrentSlide.c;
        if (!galleryInfo)
            return;
        Global.isVariety = true;
        var cardInfo = {fullDir: "", relDir: "", galleryInfo: galleryInfo, thumbData: thumbData};
        //是否是重新编辑
        if (isUpdate) {
            cardInfo.fullDir = Path.join(slide.getCurSlidePath(), 'media', _self.id);
            saveGallery(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);
            IOUtil.mkdir(cardInfo.fullDir).done(function () {
                saveGallery(cardInfo, _self);
            });
        }
    }

    /**
     * 保存文件
     * @param {object} cardInfo {fullDir,relDir,galleryInfo,thumbData}
     * fullDir画廊的完整绝对路径
     * relDir画廊的相对路径
     * galleryInfo画廊卡片的meta.json信息
     * thumbData画廊卡片的缩略图base64
     */
    function saveGallery(cardInfo, _self) {
        var slide = Global.CurrentSlide.c;
        var self = _self;
        var fullDir = cardInfo.fullDir;
        var relDir = cardInfo.relDir;
        var galleryInfo = cardInfo.galleryInfo;
        var thumbData = cardInfo.thumbData;
        var newGalleryImgSrcArr = [];
        //把绝对路径替换成只留图片名称，并拷贝图片
        for (var i = 0; i < galleryInfo.images.length; i++) {
            var src = galleryInfo.images[i].src;
            var newSrc = commands.randomString(5) + src.substring(src.lastIndexOf(".")).toLowerCase();
            var desImgPath = Path.join(fullDir, newSrc);
            if (!(desImgPath === src)) {
                IOUtil.copyFileSync(src, desImgPath);
            }
            galleryInfo.images[i].src = newSrc;
            newGalleryImgSrcArr.push(newSrc);
        }


        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], newGalleryImgSrcArr);
                if (indexFlag === -1 && fileNameArray[i] !== 'meta.json') {
                    fs.unlink(Path.join(fullDir, fileNameArray[i]));
                }
            }

            var metaPath = Path.join(fullDir, 'meta.json');
            IOUtil.writeFile(metaPath, JSON.stringify(galleryInfo)).done(function (result) {
                if (result) {
                    //将base64转为图片
                    var thumbImgPath = Path.join(fullDir, "thumbnail.png");
                    //console.log(thumbData,thumbImgPath);
                    IOUtil.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 () {
                            console.log(self.width, self.height);
                            if (self.width != 595) {
                                self.width = 650;
                            }
                            if (self.height != 473) {
                                self.height = 500;
                            }
                            if (!isUpdate) {
                                var mainSize = slide.getCanvasSize();
                                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;
                                slide.add(self);
                            }
                            slide.renderAll();
                            setTimeout(function () {
                                commands.showThumbImg(Global.CurrentSlide.c._canvas);
                            }, 100);
                        });
                    });
                } else {
                    commands.showPop("画廊卡片保存失败，请重试。");
                }
            });

        });
    }

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