/**
 * Created by ythuang 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 commands = require('editor/assert/js/utils/commands').commands;
    var isUpdate = false;
    var timeline_style = 'vertical'; //vertical、horizon
    var AppContext = require('share/assert/js/appcontext').AppContext;
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var historyTemplate = require('./historytemplate').historyTemplate;

    fabric.History.prototype.showEditDialog = function (opt, finishcallback) {
        isUpdate = false;
        timeline_style = 'vertical';
        if (opt) {
            isUpdate = true;
            this.id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
        }
        var _self = this;
        createDlg().done(function (dlg) {
            dlg.modal({show: true, keyboard: false, backdrop: "static"});

            historyTemplate.initDatas();
            historyTemplate.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);
                    if (cmd.style === 'horizon') {
                        timeline_style = 'horizon';
                        dlg.find("#btn_x").addClass('pop_btn_avtive');
                        dlg.find("#btn_y").removeClass('pop_btn_avtive');
                    } else {
                        timeline_style = 'vertical';
                        dlg.find("#btn_y").addClass('pop_btn_avtive');
                        dlg.find("#btn_x").removeClass('pop_btn_avtive');
                    }

                    var s = Global.CurrentSlide.c;
                    var wdir = Path.join(s.getCurSlidePath(), 'media', _self.id);
                    for (var i = 0; i < cmd.items.length; i++) {
                        if (cmd.items[i].img != '' && cmd.items[i].img != null) {
                            cmd.items[i].img = Path.join(wdir, cmd.items[i].img);
                        }
                    }
                    historyTemplate.setCmdText(cmd);
                });
            }

            // 绑定事件
            dlg.find("#btn_x").click(function () {
                historyTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    timeline_style = 'horizon';
                    dlg.find("#btn_x").addClass('pop_btn_avtive');
                    dlg.find("#btn_y").removeClass('pop_btn_avtive');
                });
            });
            dlg.find("#btn_y").click(function () {
                historyTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    timeline_style = 'vertical';
                    dlg.find("#btn_y").addClass('pop_btn_avtive');
                    dlg.find("#btn_x").removeClass('pop_btn_avtive');
                });
            });
            /**
             * 绑定“下一步”按钮
             */
            dlg.find("#next_step").click(function () {
                historyTemplate.timeSortComplete(function (result) {
                    if (result) {
                        historyTemplate.changeEditTime(function () {

                        });
                        setTimeout(function () {
                            historyTemplate.showTimeLine(function () {
                            });
                        }, 100);
                        dlg.find("#btn_bar1").hide();
                        dlg.find("#btn_bar2").show();
                    } else {
                        commands.showSelectorPop(commands.getErrorMsg(5050), function (_is) {

                            }, null, this, [
                            {
                                label: '确定',
                                cssClass: 'btn-primary',
                                action: function () {
                                    commands.hidePop();
                                }}
                        ]
                        );
                        return;
                    }
                });
            });
            /**
             * 绑定“上一步”按钮 到选择时间轴数量
             */
            dlg.find("#pre_step").click(function () {
                historyTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    historyTemplate.changeSelectTime(function () {

                    });
                    historyTemplate.saveCurrentTime(null);
                    historyTemplate.getTimeNum(function (num) {
                        historyTemplate.chooseTimesNum(num);
                    });

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

            /**
             * 绑定“生成”按钮 到预览
             */
            dlg.find("#btn_end").bind('click', function () {
                historyTemplate.isUEditorDlgShow(function (rtn) {
                    if (rtn) {
                        return;
                    }
                    historyTemplate.saveCurrentTime(null);
                    historyTemplate.changPreviewTime(null);
                    historyTemplate.previewTime(timeline_style);
                    dlg.find("#btn_bar2").hide();
                    dlg.find("#btn_bar3").show();
                });
            });

            /**
             * 绑定“导入案例”按钮
             */
            dlg.find('#btn_yangshi').bind('click', function () {
                var historyTemplatePath = Path.join(AppContext.getDefaultTemplate(), 'historyExample');
                IO.readFile(historyTemplatePath + "/meta.json").done(function (jsonStr) {
                    jsonStr = jsonStr.replace(/\n/g, '\\n');
                    var cmd = JSON.parse(jsonStr);
                    for (var i = 0; i < cmd.items.length; i++) {
                        if (cmd.items[i].img != '' && cmd.items[i].img != null) {
                            cmd.items[i].img = Path.join(historyTemplatePath, cmd.items[i].img);
                        }
                    }
                    historyTemplate.setCmdText(cmd);
                });
            });

            /**
             * 绑定“上一步”按钮 到编辑时间轴
             */
            dlg.find('#pre_step_one').bind('click', function () {
                historyTemplate.changeEditTime();
                dlg.find("#btn_bar3").hide();
                dlg.find("#btn_bar2").show();
            });

            /**
             * 绑定“完成”按钮
             */
            dlg.find('#btn_complete').bind('click', function () {
                historyTemplate.getHistoryInfo(timeline_style, function (historyInfo, thumbData) {
                    if (historyInfo) {
                        for (var i = 0; i < historyInfo.items.length; i++) {
                            var src = historyInfo.items[i].img;
                            if (src == null || src == 'undefined') {
                                historyInfo.items[i].img = '';
                            }
                            var title = historyInfo.items[i].title;
                            if (title == null || title == 'undefined') {
                                historyInfo.items[i].title = '';
                            }
                            var text = historyInfo.items[i].text;
                            if (text == null || text == 'undefined') {
                                historyInfo.items[i].text = '';
                            }
                        }
                        _self.saveToFile(historyInfo, thumbData);
                    }
                    dlg.modal('hide');

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

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

            /**
             * 绑定关闭按钮
             */
            dlg.on('hidden.bs.modal', function (e) {
                dlg.remove();
                Global.isEditing = false;
            })
        });
    };

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

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

        var _self = this;
        var slide = Global.CurrentSlide.c;
        if (!historyInfo)
            return;
        Global.isVariety = true;
        var cardInfo = {fullDir: "", relDir: "", historyInfo: historyInfo, thumbData: thumbData};
        //是否是重新编辑
        if (isUpdate) {
            cardInfo.fullDir = Path.join(slide.getCurSlidePath(), 'media', _self.id);
            saveHistory(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 () {
                saveHistory(cardInfo, _self);
            });
        }

    }
    fabric.History.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.History.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };
    function saveHistory(cardInfo, self) {
        var slide = Global.CurrentSlide.c;
//        var self = self;
        var fullDir = cardInfo.fullDir;
        var relDir = cardInfo.relDir;
        var historyInfo = cardInfo.historyInfo;
        var thumbData = cardInfo.thumbData;
        var newhistoryImgSrcArr = [];

        //把绝对路径替换成只留图片名称，并拷贝图片
        for (var i = 0; i < historyInfo.items.length; i++) {
            var src = historyInfo.items[i].img;
            if (src != null && typeof src != 'undefined' & src != '') {
                var newSrc = commands.randomString(5) + '.' + src.substring(src.lastIndexOf(".") + 1);
                var desImgPath = Path.join(fullDir, newSrc);
                if (!(desImgPath === src)) {
                    IO.copyFileSync(src, desImgPath);
                }
                historyInfo.items[i].img = newSrc;
                newhistoryImgSrcArr.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], newhistoryImgSrcArr);
                if (indexFlag === -1 && fileNameArray[i] !== 'meta.json') {
                    //  除meta.json以外的文件
                    fs.unlink(Path.join(fullDir, fileNameArray[i]));
                }
            }

            var metaPath = Path.join(fullDir, 'meta.json');
            IO.writeFile(metaPath, JSON.stringify(historyInfo)).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();
                            setTimeout(function () {
                                commands.showThumbImg(Global.CurrentSlide.c._canvas);
                            }, 300)

                        });
                    });
                } else {
                    commands.showPop("时间轴保存失败，请重试。");
                }
            });
        });
    }

});