/**
 * Created by liuling on 2017/5/31.
 */
var qTreeF7 = (function () {

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

    var f7 = function (treeDataUrl, dataUrl, displayFields, storeFields) {

        cfapp_treef7({
            treeDataUrl: treeDataUrl,
            treeKey: "questionsCategory",
            dataUrl: dataUrl,  //导入的action Url
            checkType: 'multi', // 多选为multi
            title: "选择问题",
            displayWidth: '900',
            btnoktext: "确定",
            btncanceltext: "取消",
            columns: ['选择', '题目类型', '题目','创建时间'],
            searchColumns:['questionTitle'],
            isSearch:'0',
            searchColumnsRemarks:['题目'],
            aoColumns: [
                {
                    "mData": "id"
                },{
                    "mData": "questionType"
                },
                {
                    "mData": "optiondetails"
                },
                {
                    "mData": "createTime"
                }],
            aoColumnDefs: [{
                "aTargets": [0],
                "mData": "id",
                "mRender": function (a, b, c, d) {//a表示createtime对应的值，c表示当前记录行对象
                    return "<input type='checkbox' id='" + a + "' name='sel' data-value='" + c.optiondetails +  "'  data-name='" + JSON.parse(c.optiondetails).title + "'>";
                }
            },{
                "aTargets": [1],
                "mData": "questionType",
                "mRender": function (a, b, c, d) {
                    var type='';
                    if(a=='SINGLESEL'){
                        type='单选';
                    }else if(a=='MULTISEL'){
                        type='多选';
                    }else if(a=='PICSEL'){
                        type='图片上传';
                    }else if(a=='BLANKFILL'){
                        type='填空';
                    }else if(a=='TRUEFALSE'){
                        type='对错';
                    }else if(a=='PICSINGLESEL'){
                        type='图片单选';
                    }else if(a=='PICMULTISEL'){
                        type='图片多选';
                    }
                    return type;
                }
            },
                {
                    "aTargets": [2],
                    "mData": "optiondetails",
                    "mRender": function (a, b, c, d) {
                        return JSON.parse(a).title;
                    }
                },
                {
                    "aTargets": [3],
                    "mData": "createTime",
                    "mRender": function (a, b, c, d) {//a表示createtime对应的值，c表示当前记录行对象
                        return formatDates(a, "yyyy-MM-dd HH:mm:ss");
                    }
                }],
            success: function () {

            },   //确定处理
            cancel: function () {

            },    // 取消的处理
            displayFields: displayFields,  //显示的字段
            storeFields: storeFields // 储存的字段
        });
    };

    var cfapp_treef7 = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            treeDataUrl: '',    //树的数据接口
            treeKey: '',    //请求的分类的字段名（分类id）
            treeKeyDefVal: 0,
            dataUrl: '',  //导入的action Url
            checkType: 'single', // 多选为multi
            //type: 'success', // alert's type
            title: "F7选择",
            btnoktext: "确定",
            btncanceltext: "取消",
            displayWidth: 'auto',
            columns: [],
            aoColumns: [],
            aoColumnDefs: [],
            success: null,   //确定处理
            cancel: null,    // 取消的处理
            displayFields: '',  //显示的字段
            storeFields: '', // 储存的字段
            isSearch:'1',  //0搜索  1：不搜索
            searchColumns:[],//搜索的字段名称
            searchColumnsRemarks:[],//搜索的字段备注
            exitsColumns:[],//已经存在的ID数组
            isShowButton:'0'//是否显示确定取消的button,0:显示，1:不显示
        }, options);
        var id = getUniqueID("cfapp_treef7");

        var MIN_WIDTH = 500;
        var MAX_WIDTH = 1000;

        var displayValue = '';
        var storeValue = '';

        var checkBox;// = options.exitsColumns;   //多选时数组

        var checkBoxName; //多选时数组
        if ($('#' + options.storeFields) && $('#' + options.storeFields).val() != '') {
            checkBox = $('#' + options.storeFields).val().split(",");
            checkBoxName = $('#' + options.displayFields).val().split(",");

            for (var i = 0, j = checkBox.length; i < j; i++) {
                var tmp = checkBox[i];
                if (tmp === undefined || tmp == '') {
                    checkBox.splice(i, 1);
                    checkBoxName.splice(i, 1);
                }
            }
        }else{
            checkBox = [];
            checkBoxName=[];
        }


        if (options.checkType == 'single') {
            displayValue = $('#' + options.displayFields).val();
            storeValue = $('#' + options.storeFields).val();
        }

        var f7Hight = window.screen.height / 2;
        var displayWidth = '';
        var displayColumnSize = options.columns.length;
        if (options.displayWidth != 'auto') {
            displayWidth = options.displayWidth + 'px';
        }

        displayWidth = displayColumnSize * 200;

        if (displayWidth <= MIN_WIDTH) {
            displayWidth = MIN_WIDTH;
        } else if (displayWidth > MAX_WIDTH) {
            displayWidth = MAX_WIDTH;
        }

        displayWidth = displayWidth + 'px';


        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' ;
        if (displayWidth == '') {
            html += '<div class="modal-dialog">';
        } else {
            html += '<div class="modal-dialog" style="width:'+displayWidth+'">';
        }
        html +=
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closemodel-' + id + '">' +
            '<span aria-hidden="true">×</span></button>' +
            '<h4 class="modal-title" id="label-' + id + '">' + options.title + '</h4>' +
            '</div>' +
            '<div class="modal-body" style="height:' + f7Hight + 'px; overflow: hidden;overflow-y:scroll;overflow-x:scroll" >' +
            '<div class="col-xs-12">'+
            '<div class="col-xs-3" style="display:none">'+
            '<div class="box">'+
            '<ul id="tree-'+id+'" class="ztree"></ul>'+
            '</div>'+
            '</div>'+
            '<div class="col-xs-12">'+
            '<div class="box">'+
            '<div class="box-header">'+
            '<form id=\"seachTableForm'+id+'\">'+
            '<div class="col-xs-2" style="display: none">'+
            '<input type="text" class="form-control required" name="'+options.treeKey+'" id="'+options.treeKey+'" placeholder="" value="'+options.treeKeyDefVal+'">'+
            '</div>';
        if(options.isSearch=='0'){//需要搜索
            for(var s = 0;s<options.searchColumns.length;s++){
                html+="<div class=\"col-xs-4\"><input type=\"text\" class=\"form-control required\" placeholder=\""+options.searchColumnsRemarks[s]+"\" name=\""+options.searchColumns[s]+"\"></div>";
            }
            html+="</form>";
            html+="<div class=\"col-xs-1\"><button   type=\"button\" class=\"submit"+id+" btn btn-primary\">搜索</button></div>";
        }
        html+='</div>'+
            '<div class="box-body">';
        html+='<table id="f7tbl-' + id + '" class="table table-bordered table-striped">' +
            '</table>' +
            '</div></div></div></div></div>' +
            '<div class="modal-footer">';
        if(options.isShowButton=='0'){
            html+='<button type="button" class="btn btn-default" id="btncancel-' + id + '">' + options.btncanceltext + '</button>' +
                '<button type="button" class="btn btn-primary" id="btnok-' + id + '">' + options.btnoktext + '</button>' ;
        }
        html+= '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var targetMessage = null;
        if (options.container == 'messages') {
            targetMessage = $(window.parent.document).find('#messages');
        } else {
            targetMessage = $('#' + options.container);
        }
        targetMessage.html(html);
        var aoData = {
            iDisplayStart: 1,
            iDosplayLength: 10
        };
        var retrieveData = function (sSource, aoData, fnCallback) {
            targetMessage.find("#seachTableForm" + id + " input,.select2").each(function () {
                var params = {
                    name : $(this).attr("name"),
                    value : $(this).val()
                };
                aoData.push(params);
            });
            $.ajax({
                "type": "GET",
                "url": sSource,
                "dataType": "json",
                "data": aoData, //以json格式传递
                "success": function(json){
                    fnCallback(json);
                    initComplete();
                }
            });
        };


        var bindTableEvent = function () {
            if (options.checkType == 'single') {
                targetMessage.find('#f7tbl-' + id).on('change', 'input[type=radio]', function () {
                    var selObj = $(this);
                    displayValue = selObj.data('name');
                    storeValue = selObj.data('value');
                });
            }
            if(options.checkType == "multi"){
                targetMessage.find('#f7tbl-' + id).on('change', 'input[type=checkbox]', function () {
                    var selObj = $(this);
                    if(selObj.is(":checked")){//选中
                        checkBox.push(JSON.parse(selObj.attr("data-value")));
                        checkBoxName.push($(this).attr("data-name"));
                    }else{//取消选中
                        checkBox.splice($.inArray($(this).attr("data-value"), checkBox), 1);
                        checkBoxName.splice($.inArray($(this).attr("data-name"), checkBoxName), 1);
                    }
                });
            }
        };

        //创建表头
        var buildTblHeader = function () {
            var htmlStr = '<thead><tr>';
            for (var i = 0, j = options.columns.length; i < j; i++) {
                var columnObj = options.columns[i];
                htmlStr += '<th>' + columnObj + '</th>';
            }
            htmlStr += '</tr></thead><tbody id="f7-body-' + id + '"></tbody>';
            targetMessage.find('#f7tbl-' + id).append(htmlStr);
            initTree();
            initTable();
            bindTableEvent();
        };
        var treeDI = targetMessage.find('#tree-'+id);

        var initTree = function () {

            var getTreeData = function () {
                $.ajax({
                    "type": "GET",
                    "contentType": "application/json",
                    "url": options.treeDataUrl,
                    "dataType": "json",
                    "success": buildTree
                });
            };

            getTreeData();
        };

        var buildTree = function (data) {
            var setting = {
                data: {simpleData: {enable: true}}, callback: {
                    beforeClick: function (id, node) {
                        var treeId = node.id;
                        targetMessage.find('#'+options.treeKey).val(treeId);
                        freshTable();
                    }
                }
            };
            var zNodes = data.aaData;
            var tree = $.fn.zTree.init(treeDI, setting, zNodes);

            tree.expandAll(true);
            tree.expandNode(tree.getNodesByFilter(function (node) {
                return node.level == 0;
            }, true), true, false, false);
            var nodes = tree.getNodes();
            tree.selectNode(nodes[0]); //选中第一个子节点
        };

        var initComplete  = function (setting) {
            if (options.checkType == 'single') {
                targetMessage.find('#f7-body-' + id).find('input[name=sel]').each(function () {
                    var chkObj = $(this);

                    if (chkObj.attr('id') == storeValue) {
                        chkObj.prop('checked', 'checked');
                    }
                });
            }
            if (options.checkType == "multi") {
                targetMessage.find('#f7-body-' + id).find('input[name=sel]').each(function () {
                    var chkObj = $(this);
                    if (checkBox.indexOf(chkObj.attr('id')) != -1) {
                        chkObj.prop('checked', 'checked');
                    }
                });
            }
        };

        var initTable = function () {
            targetMessage.find('#f7tbl-' + id).DataTable({
                "lengthChange": false,
                "searching": false,
                "ordering": false,
                "bFiltered": false,
                "bStateSave": false, // save datatable state(pagination, sort, etc) in cookie.
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": options.dataUrl,
                "fnServerData": retrieveData,
                "pagingType": "full_numbers",
                "aoColumns": options.aoColumns,
                "aoColumnDefs": options.aoColumnDefs,
                "fnInitComplete": initComplete,
                //"fnPreDrawCallback":initComplete
                //"fnCreatedRow":initComplete
            });
        };
        buildTblHeader();

        var freshTable = function () {
            targetMessage.find('#f7tbl-' + id).dataTable().fnDraw(false);
        };

        targetMessage.find(".submit"+id).click(function(){
            freshTable();
        });
        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {
            if (options.checkType == 'single') {
                $('#' + options.displayFields).val(displayValue);
                $('#' + options.storeFields).val(storeValue);
            }
            if (options.checkType == 'multi') {
                if (checkBox.length == 0) {
                    $('#' + options.storeFields).val('');
                    $('#' + options.displayFields).val('');
                } else {
                   /* qSortable = ({
                        tarId: 'queOptions',
                        data: JSON.stringify(checkBox)
                    });*/
                    qSortable.selectQuestions(JSON.stringify(checkBox));
                    /*  var names=checkBoxName;
                     var html='';
                     for(var i=0,j=checkBox.length;i<j;i++){
                     var ids=checkBox[i];
                     html+="<li class='list-group-item' data-value='"+ids+"' style='width: 30%;'>" +
                     "<span class='glyphicon glyphicon-th-list' style='margin-right:15px;'></span>" +
                     checkBoxName[i]+
                     " <button type='button' class='close' data-dismiss='modal'>&times;</button></li>";
                     }
                     $('#queOptions').append(html);*/
                    /* $('#' + options.storeFields).val(checkBox.toString() + ",");
                     $('#' + options.displayFields).val(checkBoxName.toString() + ",");*/
                }

            }
            options.success();
            $("body").removeClass("modal-open");
            $('.modal-backdrop').remove();
            targetMessage.html('');
            $("body").css("padding-right","0px");
        });
        //增加按钮绑定回调处理
        targetMessage.find('#btncancel-' + id).click(function () {
            options.cancel();
            $("body").removeClass("modal-open");
            $('.modal-backdrop').remove();
            targetMessage.html('');
            $("body").css("padding-right","0px");
        });

        //绑定关闭
        targetMessage.find('#closemodel-' + id).click(function () {
            $("body").removeClass("modal-open");
            $('.modal-backdrop').remove();
            targetMessage.html('');
            $("body").css("padding-right","0px");
        });
        targetMessage.find('#' + id).modal('show');

    };

    return {
        f7: f7,
        qtreef7:cfapp_treef7
    }
})();