/**
 * Created by liuling on 2017/5/25.
 * qtype:
 * SINGLESEL 单选
 * MULTISEL 多选
 * PICUPLOAD 图片上传
 * BLANKFILL 填空
 * TRUEFALSE 对错
 * PICSINGLESEL 图片单选
 * PICMULTISEL 图片多选
 */
var qSelect = (function () {
    'use strict';
    var QSelect = function(params) {
        var p = this;

        //参数定义
        p.params = {
            tarId: '',
            qtype: 'SINGLESEL',
            title: '单选题',
            data: null
        };


        for (var param in params) {
            p.params[param] = params[param];

        }

        var columnMap = {
            SINGLESEL: [{name:'选项标签',width: '5%'},{name:'选项内容',width: '30%'},{name:"选项内容英文",width: '30%'}],
            MULTISEL: [{name:'选项标签',width: '5%'},{name:'选项内容',width: '30%'},{name:"选项内容英文",width: '30%'}],
            PICUPLOAD: [],
            BLANKFILL: [],
            TRUEFALSE: [{name:'选项标签',width: '20%'},{name:'选项内容',width: '50%'}],
            PICSINGLESEL: [{name:'选项标签',width: '20%'},{name:'选项内容',width: '40%'}, {name:'图片',width: '30%'}],
            PICMULTISEL: [{name:'选项标签',width: '20%'},{name:'选项内容',width: '40%'}, {name:'图片',width: '30%'}]
        };

        var getUniqueID = function (prefix) {
            if (!prefix || prefix == '') prefix = 'pf';
            return prefix + '_' + Math.floor(Math.random() * (new Date()).getTime());
        };

        p.id = getUniqueID('ss');

        var tid = '#'+p.params.tarId;
        var qtype = p.params.qtype;


        Handlebars.registerHelper('display', function(pic, options) {
            if (!pic || pic === '') {
                return 'display:none';
            } else {
                return "";
            }
        });

        //单选的
        var singleSelectTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<input id="{{id}}-title" data-id="{{data.sid}}" name="title" class="form-control" type="text" placeholder="请输入题目标题" value="{{data.title}}">' +
            '<input id="{{id}}-title-en" name="title-en" class="form-control" type="text" placeholder="请输入题目标题英文" value="{{data.titleEn}}">' +
            '<input id="{{id}}-max" class="form-control" type="hidden" placeholder="最多可选几项" value="1" >'+
            '<input id="{{id}}-min" class="form-control" type="hidden" placeholder="最少可选几项" value="1">'+
            '<table id="{{id}}-options" class="table table-bordered table-striped dataTable no-footer">' +
            '{{#each columns}}' +
            '<th width="{{width}}">{{name}}</th>' +
            '{{/each}}' +
            '<th>操作</th>' +
            '{{#each data.datas}}' +
            '<tr class="option">'+
            '<td><input type="text" data-id="{{oid}}" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td><input type="text" class="option-name-en form-control" placeholder="选项名称英文" value="{{nameEn}}"></td>'+
            '<td><a href="javascript:void(0)" class="{{../id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>'+
            '{{/each}}' +
            '</table>' +
            '<p class="{{id}}-add" style="width:100%;text-align:center"><a href="javascript:void(0)">添加选项</a></p>' +
            '</div>';

        //多选的
        var multiSelectTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<div class="box box-success" style="margin-top: 10px;">'+
            '<div class="box-body">'+
                '<label>多选设置</label>'+
                '<input id="{{id}}-min" class="form-control" type="number" placeholder="最少选几项" value="{{data.min}}">'+
                '<input id="{{id}}-max" class="form-control" type="number" placeholder="最多选几项" value="{{data.max}}">'+
            '</div>'+
            '</div>'+
            '<input id="{{id}}-title" data-id="{{data.sid}}" name="title" class="form-control" type="text" placeholder="请输入题目标题" value="{{data.title}}">' +
            '<input id="{{id}}-title-en" name="title-en" class="form-control" type="text" placeholder="请输入题目标题英文" value="{{data.titleEn}}">' +
            '<table id="{{id}}-options" class="table table-bordered table-striped dataTable no-footer">' +
            '{{#each columns}}' +
            '<th width="{{width}}">{{name}}</th>' +
            '{{/each}}' +
            '<th>操作</th>' +
            '{{#each data.datas}}' +
            '<tr class="option">'+
            '<td><input type="text" data-id="{{oid}}" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td><input type="text" class="option-name-en form-control" placeholder="选项名称英文" value="{{nameEn}}"></td>'+
            '<td><a href="javascript:void(0)" class="{{../id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>'+
            '{{/each}}' +
            '</table>' +
            '<p class="{{id}}-add" style="width:100%;text-align:center"><a href="javascript:void(0)">添加选项</a></p>' +
            '</div>';
        //对错的table
        var trueFalseTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<input id="{{id}}-max" class="form-control" type="hidden" placeholder="最多可选几项" value="1">'+
            '<input id="{{id}}-min" class="form-control" type="hidden" placeholder="最少可选几项" value="1">'+
            '<input id="{{id}}-title" name="title" class="form-control" type="text" placeholder="请输入{{title}}" value="{{data.title}}" >' +
            '<table id="{{id}}-options" class="table table-bordered table-striped dataTable no-footer">' +
            '{{#each columns}}' +
            '<th width="{{width}}">{{name}}</th>' +
            '{{/each}}' +
            '{{#each data.datas}}' +
            '<tr class="option">'+
            '<td><input type="text" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '</tr>'+
            '{{/each}}' +
            '</table>' +
            '</div>';

        //单选的行
        var singleSelectTableRow =
            '<tr class="option">'+
                '<td><input type="text" data-id="{{oid}}" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
                '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td><input type="text" class="option-name-en form-control" placeholder="选项名称英文" value="{{nameEn}}"></td>'+
                '<td><a href="javascript:void(0)" class="{{id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>';

        //填空的
        var blankFillTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<div class="box box-success" style="margin-top: 10px;">'+
            '<div class="box-body">'+
            '<label>填空设置</label>'+
            '<input id="{{id}}-min" class="form-control" type="hidden" placeholder="最少可选几项" value="1">'+
            '<input id="{{id}}-max" class="form-control" type="number" placeholder="最多输入多少字" value="{{data.max}}">'+
            '</div>'+
            '</div>'+
            '<input id="{{id}}-title" data-id="{{data.sid}}" name="title" class="form-control" type="text" placeholder="请输入标题" value="{{data.title}}" >' +
            '<input id="{{id}}-title-en" name="title-en" class="form-control" type="text" placeholder="请输入标题英文" value="{{data.titleEn}}" >' +
            '</div>';

        //填空的
        var picUploadTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<div class="box box-success" style="margin-top: 10px;">'+
            '<div class="box-body">'+
            '<label>图片上传设置</label>'+
            '<input id="{{id}}-min" class="form-control" type="hidden" placeholder="最少上传几张图片" value="1">'+
            '<input id="{{id}}-max" class="form-control" type="number" placeholder="最多上传几张图片" value="{{data.max}}">'+
            '</div>'+
            '</div>'+
            '<input id="{{id}}-title" name="title" class="form-control" type="text" placeholder="请输入{{title}}" value="{{data.title}}" >' +
            '</div>';

        //图片单选的
        var singlePicSelectTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<input id="{{id}}-title" name="title" class="form-control" type="text" placeholder="请输入{{title}}" value="{{data.title}}" >' +
            '<input id="{{id}}-min" class="form-control" type="hidden" placeholder="最少可选几项" value="1">'+
            '<input id="{{id}}-max" class="form-control" type="hidden" placeholder="最多可选几项" value="1">'+
            '<table id="{{id}}-options" class="table table-bordered table-striped dataTable no-footer">' +
            '{{#each columns}}' +
            '<th width="{{width}}">{{name}}</th>' +
            '{{/each}}' +
            '<th>操作</th>' +
            '{{#each data.datas}}' +
            '<tr class="option">'+
            '<td><input type="text" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td>' +
            '<input type="text" style="display: none;" class="option-pic form-control"  value="{{pic}}" >'+
            '<div class="pic-select" style="text-align: center;line-height: 100px;width: 100px;height: 100px;border: 1px #ccc solid;position: relative;">'+
            '<i class="fa fa-plus" style="font-size:22px;color:#ccc"></i>'+
            '<img src="{{pic}}" style="width:100px;height: 100px;border:0px;position: absolute;z-index:999;left: 0px;{{display pic}};" />'+
            '</div>'+
            '</td>'+
            '<td><a href="javascript:void(0)" class="{{../id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>'+
            '{{/each}}' +
            '</table>' +
            '<p class="{{id}}-picadd" style="width:100%;text-align:center"><a href="javascript:void(0)">添加选项</a></p>' +
            '</div>';

        //单选的行
        var picSelectTableRow =
            '<tr class="option">'+
            '<td><input type="text" data-id="{{oid}}" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td><input type="text" class="option-name-en form-control" placeholder="选项名称英文" value="{{nameEn}}"></td>'+
            '<td>' +
            '<input type="text" style="display: none;" class="option-pic form-control"  value="{{pic}}" >'+
            '<div class="pic-select" style="text-align: center;line-height: 100px;width: 100px;height: 100px;border: 1px #ccc solid;position: relative;">'+
            '<i class="fa fa-plus" style="font-size:22px;color:#ccc"></i>'+
            '<img src="{{pic}}" style="width:100px;height: 100px;border:0px;position: absolute;z-index:999;left: 0px;{{display pic}}" />'+
            '</div>'+
            '</td>'+
            '<td><a href="javascript:void(0)" class="{{id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>';

        //多选的
        var multiPicSelectTableHtml =
            '<div id="{{id}}" class="form-group form-md-line-input">' +
            '<div class="box box-success" style="margin-top: 10px;">'+
            '<div class="box-body">'+
            '<label>多选设置</label>'+
            '<input id="{{id}}-min" class="form-control" type="number" placeholder="最少选几项" value="{{data.min}}">'+
            '<input id="{{id}}-max" class="form-control" type="number" placeholder="最多选几项" value="{{data.max}}">'+
            '</div>'+
            '</div>'+
            '<input id="{{id}}-title" name="title" class="form-control" type="text" placeholder="请输入{{title}}" value="{{data.title}}">' +
            '<table id="{{id}}-options" class="table table-bordered table-striped dataTable no-footer">' +
            '{{#each columns}}' +
            '<th width="{{width}}">{{name}}</th>' +
            '{{/each}}' +
            '<th>操作</th>' +
            '{{#each data.datas}}' +
            '<tr class="option">'+
            '<td><input type="text" class="option-label form-control" placeholder="选项标签" value="{{label}}"></td>'+
            '<td><input type="text" class="option-name form-control" placeholder="选项名称" value="{{name}}"></td>'+
            '<td>' +
            '<input type="text" style="display: none;" class="option-pic form-control"  value="{{pic}}" >'+
            '<div class="pic-select" style="text-align: center;line-height: 100px;width: 100px;height: 100px;border: 1px #ccc solid;position: relative;">'+
            '<i class="fa fa-plus" style="font-size:22px;color:#ccc"></i>'+
            '<img src="{{pic}}" style="width:100px;height: 100px;border:0px;display:none;position: absolute;z-index:999;left: 0px;" />'+
            '</div>'+
            '</td>'+
            '<td><a href="javascript:void(0)" class="{{../id}}-del btn btn-default btn-sm">删除</a></td>'+
            '</tr>'+
            '{{/each}}' +
            '</table>' +
            '<p class="{{id}}-picadd" style="width:100%;text-align:center"><a href="javascript:void(0)">添加选项</a></p>' +
            '</div>';

        p.buildTable = function () {
            p.changeType(qtype, p.params.title, p.params.data);
            bindEvent();
        };

        var generateHtml = function (source, datas) {
            var template = Handlebars.compile(source);
            var htmlStr = template(datas);
            return htmlStr;
        };

        var bindEvent = function() {
            $(tid).on('click','.'+p.id+'-add', function () {
                var htmlStr = generateHtml(singleSelectTableRow, {id: p.id});
                $('#'+p.id+'-options').append(htmlStr);
            });

            $(tid).on('click','.'+p.id+'-picadd', function () {
                var htmlStr = generateHtml(picSelectTableRow, {id: p.id});
                $('#'+p.id+'-options').append(htmlStr);
            });

            $(tid).on('keyup', 'input[type=number]', function () {

                var obj = $(this);
                var va = obj.val();
                //先把非数字的都替换掉，除了数字和.
                va = va.replace(/[^\d]/g, "");

                //va = va.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
                obj.val(va);
            });

            $(tid).on('click','.pic-select', function () {
                var obj = $(this);
                Cfapp.sm({
                    title: "文章小图选择",
                    success: function (data) {
                        obj.find('img').attr("src", data[0]).show();
                        obj.parent().find('.option-pic').val(data[0]);
                    }
                })
            });


            $(tid).on('click','.'+p.id+'-del', function () {
                var obj = $(this);
                obj.parent().parent().remove();
            });
        };

        p.destory = function () {
            $(tid).html('');
        };

        p.changeType = function (type, title, data) {
            title = title || p.params.title;
            qtype = type;
            var columns = columnMap[qtype];

            var datas = data || getTypeChangeValues(title, columns);
            datas.id = p.id;
            datas.columns = columns;

            var htmlStr = '';
            if (qtype === 'SINGLESEL') {
                htmlStr = generateHtml(singleSelectTableHtml,datas);

            } else if (qtype === 'MULTISEL') {
                htmlStr = generateHtml(multiSelectTableHtml,datas);

            }
             else if (qtype === 'BLANKFILL') {
                 htmlStr = generateHtml(blankFillTableHtml,datas);

             }
             //else if (qtype === 'TRUEFALSE') {
            //     htmlStr = generateHtml(trueFalseTableHtml,datas);
            // } else if (qtype === 'PICUPLOAD') {
            //     htmlStr = generateHtml(picUploadTableHtml,datas);
            // } else if (qtype === 'PICSINGLESEL') {
            //     htmlStr = generateHtml(singlePicSelectTableHtml,datas);
            //
            // }
            // else if (qtype === 'PICMULTISEL') {
            //     htmlStr = generateHtml(multiPicSelectTableHtml,datas);
            // }


            $(tid).html(htmlStr);
        };

        var getTypeChangeValues = function (title, columns) {
            var qtitle = $('#'+p.id+'-title').val();
            var qid = $('#'+p.id+'-title').attr("data-id");
            var qtitleEn = $('#'+p.id+'-title-en').val();
            if (qtype === 'SINGLESEL' || qtype === 'MULTISEL' || qtype === 'PICSINGLESEL' || qtype === 'PICMULTISEL') {

                var qoptions = [];
                $('#'+p.id + ' tr.option').each(function () {
                    var trObj = $(this);
                    var optionLabel = trObj.find('.option-label').val();
                    var optionId = trObj.find('.option-label').attr("data-id");
                    var optionName = trObj.find('.option-name').val();
                    var optionNameEn = trObj.find('.option-name-en').val();
                    var optionPic = trObj.find('.option-pic').val();
                    qoptions.push({
                        label: optionLabel,
                        name: optionName,
                        nameEn: optionNameEn,
                        pic: optionPic,
                        oid:optionId
                    });
                });

                var retObj = {
                    id: p.id,
                    title: title,
                    columns: columns,
                    data: {
                        sid:qid,
                        title: qtitle,
                        titleEn:qtitleEn,
                        datas: qoptions
                    }
                };
                console.log('--getTypeChangeValues start--');
                console.log(retObj);
                console.log('--getTypeChangeValues end--');
                return retObj;
            } else if (qtype === 'BLANKFILL' || qtype ==='PICUPLOAD') {
                var retObj = {
                    id: p.id,
                    title: title,
                    columns: columns,
                    data: {
                        title: qtitle,
                        sid:qid,
                        titleEn:qtitleEn,
                    }
                };
                console.log('--getTypeChangeValues start--');
                console.log(retObj);
                console.log('--getTypeChangeValues end--');
                return retObj;
            } else if (qtype === 'TRUEFALSE' ) {
                var tfoptions = [{label: 'A', name: '对'},{label: 'B', name: '错'}];
                var retObj = {
                    id: p.id,
                    title: title,
                    columns: columns,
                    data: {
                        title: qtitle,
                        datas: tfoptions
                    }
                };
                console.log('--getTypeChangeValues start--');
                console.log(retObj);
                console.log('--getTypeChangeValues end--');
                return retObj;
            }
        };

        p.valid = function () {
            var title = $('#'+p.id+'-title').val();
            var titleEn = $('#'+p.id+'-title-en').val();
            if (title == '') {
                return false;
            }
            if(titleEn ==''){
                return false;

            }
            $('#'+p.id + ' tr.option').each(function () {
                var trObj = $(this);
                var optionLabel = trObj.find('.option-label').val();
                var optionId = trObj.find('.option-label').attr("data-id");
                var optionName = trObj.find('.option-name').val();
                var optionNameEn = trObj.find('.option-name-en').val();
                if (optionLabel === '' || optionName === '') {
                    return false;
                }
            });

            return true;

        };

        p.getValues = function () {
            var title = $('#'+p.id+'-title').val();
            var titleId = $('#'+p.id+'-title').attr("data-id");
            var titleEn = $('#'+p.id+'-title-en').val();
            var max = $('#'+p.id+'-max').val();
            var min = $('#'+p.id+'-min').val();
            if (qtype === 'SINGLESEL' || qtype === 'MULTISEL' || qtype ==='TRUEFALSE'|| qtype ==='PICSINGLESEL'|| qtype ==='PICMULTISEL') {

                var options = [];
                $('#'+p.id + ' tr.option').each(function () {
                    var trObj = $(this);
                    var optionLabel = trObj.find('.option-label').val();
                    var optionId = trObj.find('.option-label').attr("data-id");
                    var optionName = trObj.find('.option-name').val();
                    var optionNameEn = trObj.find('.option-name-en').val();
                    var optionpic = trObj.find('.option-pic').val();
                    options.push({
                        label: optionLabel,
                        oid:optionId,
                        name: optionName,
                        nameEn:optionNameEn,
                        pic: optionpic
                    });
                });
                var retObj = {
                    title: title,
                    sid:titleId,
                    titleEn: titleEn,
                    type: qtype,
                    max: max,
                    min: min,
                    options: options
                };
                console.log('---getValues start');
                console.log(retObj);
                console.log('---getValues end');
                return retObj;
            } if (qtype === 'BLANKFILL' || qtype ==='PICUPLOAD') {

                var retObj = {
                    title: title,
                    titleEn:titleEn,
                    type: qtype,
                    sid:titleId,
                    max: max,
                    min: min,
                    options: []
                };
                console.log('---getValues start');
                console.log(retObj);
                console.log('---getValues end');
                return retObj;
            }
        }
    };

    return QSelect;
})();
