/**
 * 连线题
 * Created by hyt on 14-9-12.
 * @vision 1.0
 */
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 matchcardTemplate = require('./matchcardtemplate').matchcardTemplate;
    var isUpdate = false;

    fabric.Matchcard.prototype.showEditDialog = function (opt, finishcallback) {
        console.log('matchcard edit fired! xxxx', opt);
        isUpdate = false;
        if (opt) {
            isUpdate = true;
            this.id = opt.src.substr(opt.src.lastIndexOf("/") + 1);
        }
        var _self = this;

        var dlg = $('<div id="modal-content" class="modal fade" tabindex="-1" role="dialog">' +
            '<div class="modal-dialog test_temp" style="width: 620px;">' +
            '<div class="pop_tit">' +
            '<span class="fl">连线题</span>' +
            '<div class="w_func fr">' +
            '<a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
            '</div>' +
            '</div>' +
            '<div id="matchcardFrame" style="overflow-y:auto;overflow-x: hidden;width: 619px;height: 500px"></div>' +
            '<div class="pop_btn_box" id="btn_bar2">' +
            '<a href="javascript:;" class="pop_btn fr mrmt" id="btn_preview"><span class="pop_btn_s2">预览</span></a>' +
            '<span class="suiji fr"><input type="checkbox" style="top: 2px;cursor: default" id="btn_suiji">随机排列</span>' +
            '<a href="javascript:;" class="pop_btn fl mrmt" id="btn_yangshi"><span class="pop_btn_s2">导入样例</span></a>' +
            '</div>' +
            '<div class="pop_btn_box" id="btn_bar3" style="display: none;">' +
            '<a href="javascript:;" class="pop_btn fr mrmt" id="btn_complete"><span class="pop_btn_s2">完成</span></a>' +
            '<a href="javascript:;" class="pop_btn fl mrmt" id="btn_pre_step"><span class="pop_btn_s2">上一步</span></a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>');

        dlg.css("paddingTop", 75);
        $('body').append(dlg);
        dlg.modal({show: true, keyboard: false, backdrop: "static"});

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


        // 绑定按钮元素
        var btnPreview = dlg.find('#btn_preview');// 预览按钮
        var btnYangShi = dlg.find('#btn_yangshi'); // 导入样例按钮
        var btnPreStep = dlg.find('#btn_pre_step'); //上一步
        var btnComplete = dlg.find('#btn_complete');// 完成
        var checkboxSuiji = dlg.find('#btn_suiji');

        var matchcardFrame = dlg.find('#matchcardFrame');
        var frameDlg = $('<!--编辑-->'+
            '<div class="test_temp" id="edit_card" style="border: none;width: 600px;height: 500px;box-shadow: none; padding: 0;padding-left: 8px;">'+
            '    <div class="test_temp_tip">'+
            '        <input type="text" class="add_answer match_title" style="cursor: auto;width: 568px" placeholder="请输入标题">'+
            '    </div>'+
            '    <div class="tst_temp_step tst_temp_step2">'+
            '        <div class="card_amount" style="-webkit-user-select: none;">'+
            '            <label>请选择配对数量：</label>'+
            '            <select id="list_num" style="width: 50px;">'+
            '                <option value="2">2</option>'+
            '                <option value="3">3</option>'+
            '                <option selected value="4">4</option>'+
            '                <option value="5">5</option>'+
            '                <option value="6">6</option>'+
            '            </select>'+
            '        </div>'+
            '        <div class="lxt_temp clearfix lxt_temp2 relative">'+
            '            <!--左侧-->'+
            '            <div id="card_question_ul">'+
            '            </div>'+
            '            <!--右侧-->'+
            '            <div id="card_answer_ul">'+
            '            </div>'+
            '            <!--横线-->'+
            '            <div class="line2 absolute" id="card_list_line">'+
            '            </div>'+
            '        </div>'+
            '    </div>'+
            '</div>'+
            '<!--预览-->'+
            '<div class="test_temp" id="preview_card" style="border: none;width: 600px;height: 500px;box-shadow: none; padding: 0;padding-left: 8px;display: none">'+
            '    <div class="test_temp_tip" id="pre_card_title" style="margin-left: -8px;width: 618px;height: 43px;background: -webkit-linear-gradient(top, #f9f9f9, #e7e7e7);border-bottom: 1px solid #a6a7a6;font-size: 18px;font-weight: bold;font-family: microsoft yahei;color: #222;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">'+
            '    </div>'+
            '    <div class="tst_temp_step tst_temp_step2">'+
            '        <div class="lxt_temp clearfix lxt_temp2 relative">'+
            '            <!--左侧-->'+
            '            <div id="card_question_ul_pre">'+
            '            </div>'+
            '            <!--右侧-->'+
            '            <div id="card_answer_ul_pre">'+
            '            </div>'+
            '        </div>'+
            '    </div>'+
            '</div>');

        matchcardFrame.html(frameDlg);
        matchcardTemplate.initDatas();
        matchcardTemplate.init();

        /**
         * 绑定“导入样例”
         */
        btnYangShi.on('click', function () {
            var matchcardTemplatePath = Path.join(AppContext.getDefaultTemplate(), 'matchcardExample');
            IO.readFile(matchcardTemplatePath + "/meta.json").done(function (jsonStr) {
                jsonStr = jsonStr.replace(/\n/g, '\\n');
                var cmd = JSON.parse(jsonStr);
                for (var i = 0; i < cmd.items.question.length; i++) {
                    if (cmd.items.question[i].type === 'img') {
                        cmd.items.question[i].value = Path.join(matchcardTemplatePath, cmd.items.question[i].value);
                    }
                    if (cmd.items.answer[i].type === 'img') {
                        cmd.items.answer[i].value = Path.join(matchcardTemplatePath, cmd.items.answer[i].value);
                    }
                }
                if(cmd.israndom === true){
                    checkboxSuiji.attr('checked',true);
                    checkboxSuiji.attr('disabled','disabled');
                }
                matchcardTemplate.setCmdText(cmd);

                // 进入编辑页
                
                dlg.find("#btn_bar1").hide();
                dlg.find("#btn_bar2").show();
                dlg.find("#btn_bar3").hide();
                matchcardTemplate.createMatchCardArray();
                matchcardTemplate.showEditCard();
                matchcardTemplate.showEditCardList();
            });
        });

        /**
         * 绑定“预览”，到预览页面
         */
        btnPreview.on('click', function () {

            var isCpl = matchcardTemplate.isAllComplete();
            if (isCpl) {
                var flag = false;
                if (checkboxSuiji.is(':checked')) {
                    flag = true;
                }
                dlg.find("#btn_bar1").hide();
                dlg.find("#btn_bar2").hide();
                dlg.find("#btn_bar3").show();
                matchcardTemplate.showPreviewCard();
                matchcardTemplate.previewCardList(flag);
            } else {
                commands.showSelectorPop(commands.getErrorMsg(5052), function (_is) {
                    }, null, this, [
                    {
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function () {
                            commands.hidePop();
                        }}
                ]
                );
                return;
            }
        });

        /**
         * 绑定“上一步”，到编辑页面
         */
        btnPreStep.on('click', function () {
            dlg.find("#btn_bar1").hide();
            dlg.find("#btn_bar2").show();
            dlg.find("#btn_bar3").hide();
            matchcardTemplate.showEditCard();
        });

        /**
         * 绑定“完成”
         */
        btnComplete.on('click', function () {
            matchcardTemplate.getMatchCardInfo(function (matchcardInfo, thumbData) {
                if (matchcardInfo) {
                    _self.saveToFile(matchcardInfo, thumbData);
                }
                dlg.modal('hide');

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

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

        setTimeout(function () {
            matchcardTemplate.createMatchCardArray();
            matchcardTemplate.showEditCardList();
            if (opt) {
                dlg.find('#btn_yangshi').hide();
            }
            setCmd();
        }, 400);

        function setCmd() {
            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);
                    var s = Global.CurrentSlide.c;
                    var wdir = Path.join(s.getCurSlidePath(), 'media', _self.id);
                    for (var i = 0; i < cmd.items.question.length; i++) {
                        if (cmd.items.question[i].type == 'img') {
                            cmd.items.question[i].value = Path.join(wdir, cmd.items.question[i].value);
                        }
                        if (cmd.items.answer[i].type == 'img') {
                            cmd.items.answer[i].value = Path.join(wdir, cmd.items.answer[i].value);
                        }
                    }
                    if(cmd.israndom === true){
                        checkboxSuiji.attr('checked',true);
                        checkboxSuiji.attr('disabled','disabled');
                    }
                    matchcardTemplate.setCmdText(cmd);
                    matchcardTemplate.createMatchCardArray();
                    matchcardTemplate.showEditCardList();
                });
            }
        }

    };

    /**
     * 保存meta，以及其他文件
     * @param galleryInfo
     */
    fabric.Matchcard.prototype.saveToFile = function (matchcardInfo, thumbData) {
        var _self = this;
        var slide = Global.CurrentSlide.c;
        if (!matchcardInfo)return;

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

    function saveMatchcard(cardInfo, self) {
        var slide = Global.CurrentSlide.c;
        var fullDir = cardInfo.fullDir;
        var relDir = cardInfo.relDir;
        var matchcardInfo = cardInfo.matchcardInfo;
        var thumbData = cardInfo.thumbData;
        var newMatchcardImgSrcArr = [];

        //把绝对路径替换成只留图片名称，并拷贝图片
        for (var i = 0; i < matchcardInfo.items.question.length; i++) {
            if (matchcardInfo.items.question[i].type == 'img') {
                var questionSrc = matchcardInfo.items.question[i].value;
                var newQuestionSrc = commands.randomString(5) + '.' + questionSrc.substring(questionSrc.lastIndexOf(".") + 1);
                var desQuestionImgPath = Path.join(fullDir, newQuestionSrc);
                if (!(desQuestionImgPath === questionSrc)) {
                    IO.copyFileSync(questionSrc, desQuestionImgPath);
                }
                matchcardInfo.items.question[i].value = newQuestionSrc;
                newMatchcardImgSrcArr.push(newQuestionSrc);
            }
            if (matchcardInfo.items.answer[i].type == 'img') {
                var answerSrc = matchcardInfo.items.answer[i].value;
                var newAnswerSrc = commands.randomString(5) + '.' + answerSrc.substring(answerSrc.lastIndexOf(".") + 1);
                var desAnswerImgPath = Path.join(fullDir, newAnswerSrc);
                if (!(desAnswerImgPath === answerSrc)) {
                    IO.copyFileSync(answerSrc, desAnswerImgPath);
                }
                matchcardInfo.items.answer[i].value = newAnswerSrc;
                newMatchcardImgSrcArr.push(newAnswerSrc);
            }
        }

        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], newMatchcardImgSrcArr);
                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(matchcardInfo)).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("连线题保存失败，请重试。");
                }
            });
        });
    };

});
