/**
 * Created by liuling on 16/4/22.
 */
var js;
var Cfapp = (function () {

    //初始化验证
    var initValidate = function () {
        //增加防止SQL注入的验证
        $.validator.addMethod("htmlescape", function (value, element) {
            var re = /select|update|delete|exec|count|’|"|=|;|>|<|%/i;
            if (re.test(value)) {
                return false;
            } else {
                return true;
            }
        }, "请您不要输入特殊字符和SQL关键字!");
    };

    function replaceNull(data) {
        if (!data) {
            return "";
        } else {
            return data;
        }
    }

    function formatDates(now) {
        var now = new Date(now);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        return year + "-" + month + "-" + date + "   " + hour + ":"
            + minute + ":" + second;
    }


    //bootstrap-fileinput
    var cfapp_initFileInput = function (options) {
        options = $.extend(true, {
            allowedFileExtensions: ['jpg', 'png', 'gif'],//文件格式
            maxFileSize: 9000,//最大文件大小
            maxFileCount: 3,//最多文件数量
            dropZoneEnabled: true,//是否显示拖拽区域
            msgFilesTooMany: "选择上传的文件数量 超过允许的最大数值！",
            uploadUrl: '',//文件上传地址
            imgs: '',//图片地址 每张图片以","分隔
            ctrName: '',//图片上传区域的名称 class id
            valName: '',//图片保存的class
            showPreview: true,//是否预览
            uploadExtraData: {
                className: 'CF',
            },//上传参数
        }, options);
        var imgArr = [];
        var imgs = options.imgs;
        if (imgs != null && imgs != "") {
            imgArr = imgs.split(",");
        }
        var imgStr = [];
        var configArr = [];
        var fileCounts = 0;
        var valueName = options.valName;
        var deleteUrl = options.deleteUrl;
        for (var i = 0, j = imgArr.length; i < j; i++) {
            if (imgArr[i] != "" && imgArr[i] != null) {
                var img = imgArr[i];
                imgStr.push("<img class='kv-preview-data file-preview-image' alt='" + img + "' style='width:auto;height:180px;'  src='" + img + "' >");
                var config = {
                    caption: options.uploadExtraData.className,//标题
                    url: deleteUrl,
                    key: img,
                    extra: {id: img}
                };
                configArr.push(config);
                fileCounts++;
            }
        }
        $(valueName).attr("filecounts", fileCounts);

        var retImgs = '';//返回imgs

        $(options.ctrName).fileinput({
            language: 'zh', //设置语言
            uploadUrl: options.uploadUrl,  //上传地址
            deleteUrl: options.deleteUrl,//刪除地址
            showUpload: false, //是否显示上传按钮
            showRemove: true,//显示删除
            dropZoneEnabled: options.dropZoneEnabled,//是否显示拖拽区域
            showCaption: true,//是否显示标题
            allowedPreviewTypes: ['image'],//视图允许类型
            allowedFileTypes: ['image'],//允许文件类型
            allowedFileExtensions: ['jpg', 'png', 'gif'],//允许文件后缀
            maxFileSize: options.maxFileSize,//文件大小限制
            maxFileCount: options.maxFileCount,//文件数量限制
            initialPreview: imgStr,//图片预览
            autoReplace: false,//是否自动替换原有文件
            initialPreviewConfig: configArr,
            enctype: 'multipart/form-data',//数据类型
            validateInitialCount: true,
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            uploadExtraData: options.uploadExtraData,//额外参数
        }).on("filebatchselected", function (event, files) {
            /*$(valueName).val("");
             fileCounts=0;*/
            if (fileCounts < options.maxFileCount) {
                //$(this).fileinput("upload");//选择完成自动上传
            } else {
                alert("最多可选择" + options.maxFileCount + "张!");
                $(this).fileinput("refresh");
            }
        }).on("fileuploaded", function (event, data) {
            retImgs += data.response.data;//目前无法对上传是否成功做处理 后续使用中再看情况
            fileCounts++;
            var oldImgs = $(options.valName).val();
            $(valueName).val(oldImgs + retImgs);//上传完成后写入返回id
            $(valueName).attr("filecounts", fileCounts);
        }).on('filedeleted', function (event, key) {
            var oldImgs = $(options.valName).val();
            oldImgs = oldImgs.replace(key + ",", "");
            $(valueName).val(oldImgs);
            fileCounts--;
            $(valueName).attr("filecounts", fileCounts);
        });

    };


    //alert处理
    var cfapp_alert = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            type: 'success', // alert's type
            title: "提示",
            message: "", // alert's message
            btntext: "确定",
            success: null   //回调处理
        }, options);
        var id = getUniqueID("Cfapp_alert");

        var html =
            '<div class="modal fade" data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h4 class="modal-title" id="label-' + id + '">' + options.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '<p>' + options.message + '</p>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-primary" id="btn-' + id + '">' + options.btntext + '</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        //清空
        var targetMessage = null;
        if (options.container == 'messages') {
            targetMessage = $(window.parent.document).find('#messages');
        } else {
            targetMessage = $('#' + options.container);
        }
        targetMessage.html(html);
        //增加按钮绑定回调处理
        $(window.parent.document).find('#btn-' + id).click(function () {
            options.success();
            $(".modal-backdrop").fadeOut();
            $(".modal-backdrop").remove();
            $("body").removeClass("modal-open");
            $("body").css("padding-right", "0px");
            $(window.parent.document).find('#' + id).remove();
        });

        //绑定关闭
        $(window.parent.document).find('#closemodel-' + id).click(function () {
            targetMessage.html('');
            $(".modal-backdrop").fadeOut();
            $(".modal-backdrop").remove();
            $("body").removeClass("modal-open");
            $("body").css("padding-right", "0px");
            $(window.parent.document).find('#' + id).remove();
        });
        $(window.parent.document).find('#' + id).modal('show');
        /* -- 当前页面弹出message
         $('#'+options.container).html('');
         //加入model
         $('#'+options.container).html(html);
         //增加按钮绑定回调处理
         $('#btn-'+id).click(function() {
         options.success();
         });

         //绑定关闭
         $('#closemodel-'+id).click(function() {
         $('#'+options.container).html('');
         });
         $('#'+id).modal('show');
         */

    };


    //confirm处理
    var cfapp_confirm = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            type: 'success', // alert's type
            title: "提示",
            message: "", // alert's message
            btnoktext: "确定",
            btncanceltext: "取消",
            success: null,   //确定处理
            cancel: null
        }, options);
        var id = getUniqueID("Cfapp_alert");

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h4 class="modal-title" id="label-' + id + '">' + options.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '<p>' + options.message + '</p>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<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>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var targetMessage = null;
        if (options.container == 'messages') {
            targetMessage = $(window.parent.document).find('#messages');
        } else {
            targetMessage = $('#' + options.container);
        }
        targetMessage.html(html);
        //增加按钮绑定回调处理
        $(window.parent.document).find('#btnok-' + id).click(function () {
            options.success();
            $(".modal-backdrop").fadeOut();
            $("body").removeClass("modal-open");
            $("body").css("padding-right", "0px");
            $(window.parent.document).find('#' + id).remove();
            $(window.parent.document).find('#' + id).remove();
        });
        //增加按钮绑定回调处理
        $(window.parent.document).find('#btncancel-' + id).click(function () {
            options.cancel();
            $("body").css("padding-right", "0px");
            $(".modal-backdrop").fadeOut();
            $("body").removeClass("modal-open");
            $(window.parent.document).find('#' + id).remove();
            $(window.parent.document).find('#' + id).remove();
        });

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

        /*--当前页面的处理
         //增加按钮绑定回调处理
         $('#btnok-'+id).click(function() {
         options.success();
         });
         $('#btncancel-'+id).click(function() {
         options.cancel();
         });
         //绑定关闭
         $('#closemodel-'+id).click(function() {
         $('#'+options.container).html('');
         });
         $('#'+id).modal('show');
         */

    };

    var cfapp_treeSingleSelect = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            url: '',
            type: 'success', // alert's type
            title: "提示",
            btnoktext: "确定",
            btncanceltext: "取消",
            success: null,   //确定处理
            cancel: null,
            displayFields: '',  //显示的字段
            storeFields: '' // 储存的字段
        }, options);
        var id = getUniqueID("Cfapp_treeselect");

        var treeSelectHight = window.screen.height / 2;

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<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:' + treeSelectHight + 'px; overflow: hidden;overflow-y:scroll" >' +
            '<ul id="tree-' + id + '" class="ztree"></ul>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<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>' +
            '</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 tree = null;

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

        var fnCallback = function (data) {
            var setting = {
                check: {enable: true, chkStyle: "radio", radioType: "all"}, view: {selectedMulti: false},
                data: {simpleData: {enable: true}}, callback: {
                    beforeClick: function (id, node) {
                        tree.checkNode(node, !node.checked, true, true);
                        return false;
                    }
                }
            };
            var zNodes = data.aaData;
            tree = $.fn.zTree.init(targetMessage.find("#tree-" + id), setting, zNodes);
            // 不选择父节点
            tree.setting.check.chkboxType = {"Y": "ps", "N": "s"};
            // 默认选择节点
            var ids = $('#' + options.storeFields).val().split(',');
            for (var i = 0, j = ids.length; i < j; i++) {
                var node = tree.getNodeByParam("id", ids[i]);
                try {
                    tree.checkNode(node, true, false);
                } catch (e) {
                }
            }
            tree.expandAll(false);
            tree.expandNode(tree.getNodesByFilter(function (node) {
                return node.level == 0;
            }, true), true, false, false);
        };

        getData();

        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {

            var checkedNodes = tree.getCheckedNodes(true);

            var checkedNames = [];
            var checkedIds = [];

            for (var i = 0, j = checkedNodes.length; i < j; i++) {
                var node = checkedNodes[i];
                var state = node.check_Child_State;

                checkedNames.push(node.name);
                checkedIds.push(node.id);

            }
            $('#' + options.displayFields).val(checkedNames[0]);
            $('#' + options.storeFields).val(checkedIds[0]);
            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');

    };

    var cfapp_treeSelect = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            url: '',
            type: 'success', // alert's type
            title: "提示",
            btnoktext: "确定",
            btncanceltext: "取消",
            success: null,   //确定处理
            cancel: null,
            displayFields: '',  //显示的字段
            storeFields: '' // 储存的字段
        }, options);
        var id = getUniqueID("Cfapp_treeselect");

        var treeSelectHight = window.screen.height / 2;

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<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:' + treeSelectHight + 'px; overflow: hidden;overflow-y:scroll" >' +
            '<ul id="tree-' + id + '" class="ztree"></ul>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<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>' +
            '</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 tree = null;

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

        var fnCallback = function (data) {
            var setting = {
                check: {enable: true, nocheckInherit: true}, view: {selectedMulti: false},
                data: {simpleData: {enable: true}}, callback: {
                    beforeClick: function (id, node) {
                        tree.checkNode(node, !node.checked, true, true);
                        return false;
                    }
                }
            };
            var zNodes = data.aaData;
            tree = $.fn.zTree.init(targetMessage.find("#tree-" + id), setting, zNodes);
            // 不选择父节点
            tree.setting.check.chkboxType = {"Y": "ps", "N": "s"};
            // 默认选择节点
            var ids = $('#' + options.storeFields).val().split(',');
            for (var i = 0, j = ids.length; i < j; i++) {
                var node = tree.getNodeByParam("id", ids[i]);
                try {
                    tree.checkNode(node, true, false);
                } catch (e) {
                }
            }
            tree.expandAll(false);
            // tree.expandNode(tree.getNodesByFilter(function (node) {
            //     return node.level == 0;
            // }, true), true, false, false);
        };

        getData();

        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {

            var checkedNodes = tree.getCheckedNodes(true);

            var checkedNames = [];
            var checkedIds = [];

            for (var i = 0, j = checkedNodes.length; i < j; i++) {
                var node = checkedNodes[i];
                var state = node.check_Child_State;
                //删除省节点
                /*if (state == -1 || state == 2) {
                 checkedNames.push(node.name);
                 checkedIds.push(node.id);
                 }*/
                //if (state == -1) {
                    checkedNames.push(node.name);
                    checkedIds.push(node.id);
                //}
            }
            $('#' + options.displayFields).text(checkedNames.join(','));
            $('#' + options.storeFields).text(checkedIds.join(','));
            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');

        /*--当前页面的处理
         //增加按钮绑定回调处理
         $('#btnok-'+id).click(function() {
         options.success();
         });
         $('#btncancel-'+id).click(function() {
         options.cancel();
         });
         //绑定关闭
         $('#closemodel-'+id).click(function() {
         $('#'+options.container).html('');
         });
         $('#'+id).modal('show');
         */

    };

    var cfapp_warning = function (options) {
        var p = this;
        options = $.extend(true, {
            container: "warning", // alerts parent container(by default placed after the page breadcrumbs)
            content: '',  //
            title: "提示"
        }, options);
        var id = getUniqueID("cfapp_warning");
        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content" style="background-color:transparent">' +
            '<div class="modal-body">' +
            '<div class="alert alert-warning alert-dismissible">' +
            '<h4><i class="icon fa fa-warning"></i>' + options.title + '</h4>' +
            options.content +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        var targetMessage = $(window.parent.document).find('#' + options.container);
        targetMessage.html(html);

        var destory = function () {
            $("body").removeClass("modal-open");
            $('.modal-backdrop').remove();
            $("body").css("padding-right", "0px");
            targetMessage.html('');
        };
        targetMessage.find('#' + id).modal('show');

        return {
            destory: destory
        }
    };

    var getQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    };

    var cfapp_importexcel = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            importurl: '',  //导入的action Url
            templateurl: '', // 下载模版的action Url
            type: 'success', // alert's type
            title: "信息导入",
            btnoktext: "导入",
            btncanceltext: "取消",
            success: null,   //确定处理
            cancel: null    // 取消的处理
        }, options);
        var id = getUniqueID("cfapp_importexcel");

        //var treeSelectHight = window.screen.height / 2;
        var csrfheader = getQueryString('_csrf_header');
        var csrftoken = getQueryString('_csrf');
        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog">' +
            '<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 ;
            if(options.templateurl){
                html+='<a href="' + options.templateurl + '" class="btn btn-info btn-sm">下载模板</a>';
            }
            html+='</h4>' +
            '</div>' +
            '<form id="form-' + id + '" enctype="multipart/form-data">' +
                '<input type="hidden" name="_csrf_header" value="'+csrfheader+'">'+
                '<input type="hidden" name="_csrf" value="'+csrftoken+'">'+
            '<div class="modal-body"  >' +
            '<label class="control-label">选择文件</label>' +
            '<input id="file" name="file" type="file">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" id="btncancel-' + id + '">' + options.btncanceltext + '</button>' +
            '<input class="btn btn-primary" id="btnok-' + id + '" value="' + options.btnoktext + '">' +
            '</div>' +
            '</form>' +
            '</div>' +
            '</div>' +
            '</div>';



        var targetMessage = $(window.parent.document).find('#messages');
        targetMessage.html(html);


        //初始化fileinput控件（第一次初始化）
        var control = targetMessage.find('#file');
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/a/a', //上传的地址
            showUpload: false, //是否显示上传按钮
            showCaption: true,//是否显示标题
            showPreview: false,
            browseClass: "btn btn-primary", //按钮样式
            previewFileIcon: "",
        });
        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {
            var file_obj = targetMessage.find('#file')[0].files[0];
            $("body").removeClass("modal-open");
            $('.modal-backdrop').remove();
           var ssaddd = cfapp_warning({
                content: '正在导入中，请稍后!',  //
                title: "提示"
            });


            //targetMessage.find("form").submit();
            //var form = new FormData(document.getElementById("form-"+id));
            var form = new FormData();
            form.append('file', file_obj);
            targetMessage.html('');
            $("body").css("padding-right", "0px");
            $.ajax({
                url: options.importurl,
                type:"post",
                data: form,
                processData:false,
                timeout:1000*60*10,
                contentType:false,
                success:function(data){
                    ssaddd.destory();
                    if(data.errorNo=="0"){
                        cfapp_alert({
                            message: data.errorMsg||'导入成功',
                            btntext: "确定",
                            success: function () {
                                options.success();
                            }
                        });
                    }

                },
                error:function(e){
                    ssaddd.destory();
                    cfapp_alert({
                        message: "导入失败",
                        btntext: "确定",
                        success: function () {
                            return;
                        }
                    });
                }
            });






        });
        //增加按钮绑定回调处理
        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');

    };

    var cfapp_sm = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            checkType: 'single', // 多选为multi
            title: "选择素材",
            btnoktext: "确定",
            btncanceltext: "取消",
            success: null,   //确定处理
            cancel: null    // 取消的处理
        }, options);

        var id = getUniqueID("cfapp_sm");
        var returnValues = [];
        var f7Hight = window.screen.height / 2;

        var smUri = 'a/materialUpload/listData';

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">';
        html += '<div class="modal-dialog">';
        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" >';
        html += '<form id=\"seachTableForm' + id + '\">';
        html += '<div class="col-xs-4">' +
            '<input type="text" class="form-control required" ' +
            'placeholder="素材标题" name="title">' +
            '</div>';
        html += "</form>";
        html += "<div class=\"col-xs-1\"><button   type=\"button\" class=\"submit" + id + " btn btn-primary\">搜索</button></div>";
        html += '<table id="f7tbl-' + id + '" class="table table-bordered table-striped">' +
            '</table>' +
            '</div>' +
            '<div class="modal-footer">';
        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>';
        var targetMessage = null;
        if (options.container == 'messages') {
            targetMessage = $(window.parent.document).find('#messages');
        } else {
            targetMessage = $('#' + options.container);
        }
        targetMessage.html(html);

        var aoData = {
            iDisplayStart: 1,
            iDisplayLength: 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 initComplete = function (setting) {
            if (options.checkType == 'single') {
                targetMessage.find('#f7-body-' + id).find('input[name=sel]').each(function () {
                    var chkObj = $(this);

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

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

        var buildTblHeader = function () {
            var htmlStr = '<thead><tr>';
            htmlStr += '<td>选择</td>' +
                '<td>标题</td>' +
                '<th>图片</th>' +
                '<th>存储位置</th>' +
                '<th>创建时间</th>';
            htmlStr += '</tr></thead><tbody id="f7-body-' + id + '"></tbody>';
            targetMessage.find('#f7tbl-' + id).append(htmlStr);
            initTable();
            bindTableEvent();
        };

        var aoColumns = [
            {
                "mData": "id"
            }, {
                "mData": "title"
            },
            {
                "mData": "url"
            },
            {
                "mData": "uploadType"
            }, {
                "mData": "createTime"
            }];
        var protocol = window.location.protocol;
        var host = window.location.host;
        var aoColumnDefs = [
            { // set default column settings
                'visible': true,
                'targets': [0],
                "mRender": function (a, b, c, d) {//a表示createtime对应的值，c表示当前记录行对象
                    /*if (c.uploadType == 'local') {
                        c.url=protocol + '//' + host + c.url;
                    }*/
                    if (options.checkType == 'single') {
                        return '<input type="radio" id="' + a + '" name="sel" data-value="' + c.url + '">';
                    } else {
                        return '<input type="checkbox" id="' + a + '" name="sel" data-value="' + c.url + '">';
                    }

                }
            }, {
                "aTargets": [2],
                "mData": "url",
                "mRender": function (a, b, c, d) {
                    var rtHtml = '';
                    if (c.uploadType == 'local') {
                        rtHtml = '<img width="80px"  src="' + a + '">';
                    } else {
                        rtHtml = '<img width="80px"  src="' + a + '">';
                    }
                    return rtHtml;
                }
            }, {
                "aTargets": [3],
                "mData": "uploadType",
                "mRender": function (a, b, c, d) {
                    var rtHtml = '';
                    if (a == 'local') {
                        rtHtml = '本地'
                    } else if (a == 'qcloud') {
                        rtHtml = '腾讯'
                    } else if (a == 'ali') {
                        rtHtml = '阿里'
                    } else if (a == 'qiniu') {
                        rtHtml = '七牛'
                    }
                    return rtHtml;
                }
            }, {
                "aTargets": [4],
                "mData": "createTime",
                "mRender": function (a, b, c, d) {
                    if (a) {
                        return formatDates(a);
                    } else {
                        return "";
                    }
                }
            }
        ];

        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": smUri,
                "fnServerData": retrieveData,
                "pagingType": "full_numbers",
                "aoColumns": aoColumns,
                "aoColumnDefs": aoColumnDefs,
                "fnInitComplete": initComplete
            });
        };
        buildTblHeader();
        targetMessage.find(".submit" + id).click(function () {
            targetMessage.find('#f7tbl-' + id).dataTable().fnDraw(false);
        });
        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {

            options.success(returnValues);
            $("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');
    };

    var cfapp_f7 = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            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_f7");

        var MIN_WIDTH = 500;
        var MAX_WIDTH = 1000;

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

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

        var checkBoxName; //多选时数组
        if ($('#' + options.storeFields) && $('#' + options.storeFields).val() && $('#' + 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" >' +
            '<form id=\"seachTableForm' + id + '\">';
        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 += '<table id="f7tbl-' + id + '" class="table table-bordered table-striped">' +
            '</table>' +
            '</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[name=sel]', function () {
                    var selObj = $(this);
                    if ($(this).is(":checked")) {//选中
                        checkBox.push($(this).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);
                    }
                });

                targetMessage.find('#f7tbl-' + id).on('change', 'input[name="f7SelectAll"]', function () {
                    var checked = $(this).is(":checked");
                    targetMessage.find('#f7-body-' + id).find('input[name=sel]').each(function () {
                        var chkObj = $(this);
                        if (checked) {//选中
                            if ($.inArray(chkObj.attr("data-value"), checkBox) == -1) {
                                checkBox.push(chkObj.attr("data-value"));
                                checkBoxName.push(chkObj.attr("data-name"));
                                chkObj.prop('checked', 'checked');
                            }
                        } else {
                            checkBox.splice($.inArray(chkObj.attr("data-value"), checkBox), 1);
                            checkBoxName.splice($.inArray(chkObj.attr("data-name"), checkBoxName), 1);
                            chkObj.prop('checked', false);
                        }

                    });
                });
            }
        };

        //创建表头
        var buildTblHeader = function () {
            var htmlStr = '<thead><tr>';
            for (var i = 0, j = options.columns.length; i < j; i++) {
                var columnObj = options.columns[i];
                if (columnObj == '选择' && options.checkType == "multi") {
                    htmlStr += '<th><input type="checkbox" id="f7SelectAll" name="f7SelectAll">' + columnObj + '</th>';
                } else {
                    htmlStr += '<th>' + columnObj + '</th>';
                }
            }
            htmlStr += '</tr></thead><tbody id="f7-body-' + id + '"></tbody>';
            targetMessage.find('#f7tbl-' + id).append(htmlStr);
            initTable();
            bindTableEvent();
        };
        var flag = 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('#f7tbl-' + id).find('input[name="f7SelectAll"]').prop('checked', false);
                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();

        targetMessage.find(".submit" + id).click(function () {
            targetMessage.find('#f7tbl-' + id).dataTable().fnClearTable();
        });
        //增加按钮绑定回调处理
        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 {
                    $('#' + 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');

    };

    var cfapp_map = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            type: 'success', // alert's type
            title: "选取地图",
            btnoktext: "确定",
            btncanceltext: "取消",
            addressField: '', //地址名称回写
            lngField: '',   // 经度回写
            latField: '',   // 纬度回写
            success: null,   //确定处理
            cancel: null    // 取消的处理
        }, options);
        var id = getUniqueID("cfapp_map");

        var mapHight = window.screen.height / 2;

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog" style="width:90%;">' +
            '<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 + '' +
            '<div class="input-group">' +
            '<input type="text" id="localsearch-' + id + '" placeholder="输入地址后搜索" class="form-control">' +
            '<span class="input-group-btn"><button type="button" id="search-' + id + '" class="btn btn-primary">搜索</button> </span>' +
            '</div>' +
            '</h4>' +
            '</div>' +
            '<div class="modal-body" style="height:' + mapHight + 'px; overflow: hidden;overflow-y:scroll" >' +
            '<div id="map-' + id + '" style="width: 100%;height: 300px;"></div>' +
            '<div id="result-' + id + '" style="width: 100%;height: 100px;"></div>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" id="btncancel-' + id + '">' + options.btncanceltext + '</button>' +
            '<input class="btn btn-primary" id="btnok-' + id + '" value="' + options.btnoktext + '" type="submit">' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';


        var targetMessage = $('#baidumap');
        targetMessage.html(html);
        var map = null;
        var local = null;
        var data = null;
        var initMap = function () {
            map = new BMap.Map("map-" + id);
            var point = new BMap.Point(116.486412, 39.92149);
            var tarPoint = null;

            if ($("#" + options.lngField).val() && $("#" + options.latField).val()) {
                tarPoint = new BMap.Point($("#" + options.lngField).val(), $("#" + options.latField).val());
            }

            map.centerAndZoom(point, 12);

            map.enableScrollWheelZoom(true);
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            map.addControl(new BMap.OverviewMapControl());
            map.addControl(new BMap.MapTypeControl());

            var geolocation = new BMap.Geolocation();
            if (tarPoint == null) {
                geolocation.getCurrentPosition(function (r) {
                    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                        var mk = new BMap.Marker(r.point);
                        map.addOverlay(mk);
                        map.panTo(r.point);
                    }
                    else {
                        alert('failed' + this.getStatus());
                    }
                }, {enableHighAccuracy: true});
            } else {
                var mk = new BMap.Marker(tarPoint);
                map.addOverlay(mk);
                window.setTimeout(function () {
                    map.panTo(tarPoint);
                }, 1500);

            }
            local = new BMap.LocalSearch(map, {
                renderOptions: {map: map, panel: "result-" + id},
                onSearchComplete: function (results) {
                    data = results;
                }
            });
            $('#search-' + id).on('click', function () {
                var searchTxt = $('#localsearch-' + id).val();
                local.search(searchTxt);
            });
        };
        initMap();
        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {
            $('#result-' + id + ' li>div').each(function (index) {
                var tobj = $(this);
                if (tobj.css('background-color') == 'rgb(240, 240, 240)') {
                    console.log(data);
                    var poiObj = data.Ir[index];//data.ur ? data.ur[index] : data.vr[index];
                    var address = poiObj.title;
                    var lat = poiObj.point.lat;
                    var lng = poiObj.point.lng;
                    $('#' + options.addressField).val(address);
                    $('#' + options.latField).val(lat);
                    $('#' + options.lngField).val(lng);
                }

            });
            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');

    };

    var cfapp_tenctentmap = function (options) {
        options = $.extend(true, {
            container: "messages", // alerts parent container(by default placed after the page breadcrumbs)
            type: 'success', // alert's type
            title: "选取地图",
            btnoktext: "确定",
            btncanceltext: "取消",
            addressField: '', //地址名称回写
            lngField: '',   // 经度回写
            latField: '',   // 纬度回写
            mapFileId:'', //回写位置id
            success: null,   //确定处理
            cancel: null    // 取消的处理
        }, options);
        var id = getUniqueID("cfapp_tenctentmap");

        var mapHight = window.screen.height / 2;

        var html =
            '<div class="modal fade"  data-backdrop="static" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="label-' + id + '" aria-hidden="true">' +
            '<div class="modal-dialog" style="width:90%;">' +
            '<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 + '' +
            '<div class="input-group">' +
            '<input type="text" id="localsearch-' + id + '" placeholder="输入城市" class="form-control" style="width:46%;margin-right:3px;">' +
            '<input type="text" id="poisearch-' + id + '" placeholder="输入地点" class="form-control" style="width:46%;margin-right:3px;">' +
            '<span class="input-group-btn"><button type="button" id="search-' + id + '" class="btn btn-primary">搜索</button> </span>' +
            '</div>' +
            '</h4>' +
            '</div>' +
            '<div class="modal-body" style="height:' + mapHight + 'px; overflow: hidden;" >' +
            '<div id="map-' + id + '" style="width: 100%;height: 300px;"></div>' +
            '<div id="result-' + id + '" style="width: 100%;height: 200px;    overflow-y: scroll;"></div>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" id="btncancel-' + id + '">' + options.btncanceltext + '</button>' +
            '<input class="btn btn-primary" id="btnok-' + id + '" value="' + options.btnoktext + '" type="submit">' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';


        var targetMessage = $('#tencentmap');
        targetMessage.html(html);
        var map = null;
        var searchService=null;
        var data = null;

        var initMap = function () {
            var center = new qq.maps.LatLng(39.916527, 116.397128);//初始化中心坐标
            if ($("#" + options.lngField).val() && $("#" + options.latField).val()) {
                center = new qq.maps.LatLng($("#" + options.lngField).val(), $("#" + options.latField).val());
            }
            map = new qq.maps.Map("map-" + id,{
                center:center,
                zoom: 13
            });
            //设置Poi检索服务，用于本地检索、周边检索
            var resultId='result-'+id;
            searchService = new qq.maps.SearchService({
                panel:resultId,
                map : map,
                complete: function(results) {
                    if(results.type=="POI_LIST"){
                        data=results.detail.pois;
                    }else{
                        data=[];
                    }
                }
            });

            function getResult() {
                //设置searchRequest
                var searchTxt = $('#localsearch-' + id).val();
                var poiText=$('#poisearch-' + id).val();
                searchService.setLocation(searchTxt);
                searchService.search(poiText);
            }

            $('#search-' + id).on('click', function () {
                getResult();
            });
        };
        initMap();
        //增加按钮绑定回调处理
        targetMessage.find('#btnok-' + id).click(function () {
            $('#result-' + id + ' li').each(function (index) {
                var tobj = $(this);
                if (tobj.css('background-color') == 'rgb(238, 238, 238)') {
                    console.log(data);
                    var poiObj = data[index];
                    if(poiObj){
                        var address = poiObj.address;
                        var lat = poiObj.latLng.lat;
                        var lng = poiObj.latLng.lng;
                        var mapId=poiObj.id;
                        $('#' + options.addressField).val(address);
                        $('#' + options.latField).val(lat);
                        $('#' + options.lngField).val(lng);
                        $('#'+options.mapFileId).val(mapId);
                    }
                }
            });
            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');

    };

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


    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">' +
            '<div class="box">' +
            '<ul id="tree-' + id + '" class="ztree"></ul>' +
            '</div>' +
            '</div>' +
            '<div class="col-xs-9">' +
            '<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] + "\" onkeydown='if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}'></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 ($(this).is(":checked")) {//选中
                        checkBox.push($(this).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 {
                    $('#' + 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 {
        init: function () {
            //验证
            initValidate();
        },
        getUniqueID: getUniqueID,
        alert: cfapp_alert,
        confirm: cfapp_confirm,
        treeSelect: cfapp_treeSelect,
        treeSingleSelect: cfapp_treeSingleSelect,
        importExcel: cfapp_importexcel,
        f7: cfapp_f7,
        treef7: cfapp_treef7,
        sm: cfapp_sm,
        map: cfapp_map,
        tencentMap:cfapp_tenctentmap,
        initFileInput: cfapp_initFileInput,
        warning: cfapp_warning
    }
})();