/**
 *  练习--分类题
 * Created by ythuang on 14-7-17.
 * @vision 1.0
 */
define(function (require, exports, modules) {
    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 pickCardTemplate = require('./pickcardtemplate').pickCardTemplate;
    var isUpdate = false;

    fabric.Pickcard.prototype.showEditDialog = function (opt) {
        console.log('Pickcard edit fired! xxxx', opt);
        isUpdate = false;
        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"});
            dlg.on('hidden.bs.modal', function (e) {
                dlg.remove();
                Global.isEditing = false;
            });

            pickCardTemplate.initDatas();
            pickCardTemplate.init();

            /**
             * 绑定“下一步”按钮 到编辑
             */
            dlg.find("#btn_sec").click(function () {
                pickCardTemplate.showEditPickCard();
                pickCardTemplate.createPickCardItems();
                pickCardTemplate.showPickCardList();

                dlg.find("#btn_sec").parents("div").hide();
                dlg.find("#btn_pre").parents("div").show();
            });

            /**
             * 绑定“上一步”按钮 到选择
             */
            dlg.find("#btn_pre").click(function () {
                pickCardTemplate.showSelectPickCard();
                dlg.find("#btn_pre").parents("div").hide();
                dlg.find("#btn_sec").parents("div").show();
            });

            /**
             * 绑定“生成”按钮 到预览
             */
            dlg.find("#btn_end").click(function () {
                dlg.find("#btn_bar2").hide();
                dlg.find("#btn_bar3").show();
                pickCardTemplate.showPreviewPickCard();
                pickCardTemplate.previewPickcard();
            });

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

            /**
             * 绑定“完成”按钮
             */
            dlg.find('#btn_complete').bind('click', function () {
                pickCardTemplate.getPickCardInfo(function (pickcardInfo, thumbData) {
                    if (pickcardInfo) {
                        _self.saveToFile(pickcardInfo, thumbData);
                    }
                    dlg.modal('hide');

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

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

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


            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.options.length; i++) {
                        if (cmd.options[i].type === 'img') {
                            cmd.options[i].value = Path.join(wdir, cmd.options[i].value);
                        }
                    }
                    pickCardTemplate.setCmdText(cmd);
                });
            }
        });
    }

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

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

    fabric.Pickcard.prototype.hidePropertyButton = function () {
        commands.usePropertyCtrlArea(null);
    };
    fabric.Pickcard.prototype.showPropertyButton = function () {
        commands.usePropertyCtrlArea('object');
    };
    function savePickCard(cardInfo, self) {
        var slide = Global.CurrentSlide.c;
        var fullDir = cardInfo.fullDir;
        var relDir = cardInfo.relDir;
        var pickcardInfo = cardInfo.pickcardInfo;
        var thumbData = cardInfo.thumbData;
        var newPickcardImgSrcArr = [];

        //把绝对路径替换成只留图片名称，并拷贝图片
        for (var i = 0; i < pickcardInfo.options.length; i++) {
            if (pickcardInfo.options[i].type === 'img') {
                var src = pickcardInfo.options[i].value;
                var newSrc = commands.randomString(5) + '.' + src.substring(src.lastIndexOf(".") + 1);
                var desImgPath = Path.join(fullDir, newSrc);
                if (!(desImgPath === src)) {
                    IO.copyFileSync(src, desImgPath);
                }
                pickcardInfo.options[i].value = newSrc;
                newPickcardImgSrcArr.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], newPickcardImgSrcArr);
                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(pickcardInfo)).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 () {

                            self.width = 715;
                            self.height = 572;

                            if (!isUpdate) {
                                self.width = 715;
                                self.height = 572;
                                self.scaleX = 1.1;
                                self.scaleY = 1.1;
                                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("分类题保存失败，请重试。");
                }
            });
        });
    }

});