var Feng = {
    ctxPath: "",
    addCtx: function (ctx) {
        if (this.ctxPath == "") {
            this.ctxPath = ctx;
        }
    },
    confirm: function (tip, ensure) {//询问框
        parent.layer.confirm(tip, {
            btn: ['确定', '取消']
        }, function (index,layero) {
            var btn = layero.find(".layui-layer-btn0");
            btn.css("pointer-events","none")
            ensure();
            parent.layer.close(index);
        }, function (index) {
            parent.layer.close(index);
        });
    },
    log: function (info) {
        console.log(info);
    },
    alert: function (info, iconIndex) {
        parent.layer.msg(info, {
            icon: iconIndex
        });
    },
    info: function (info) {
        Feng.alert(info, 0);
    },
    success: function (info) {
        Feng.alert(info, 1);
    },
    error: function (info) {
        Feng.alert(info, 2);
    },
    infoDetail: function (title, info) {
        var display = "";
        if (typeof info == "string") {
            display = info;
        } else {
            if (info instanceof Array) {
                for (var x in info) {
                    display = display + info[x] + "<br/>";
                }
            } else {
                display = info;
            }
        }
        parent.layer.open({
            title: title,
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['950px', '600px'], //宽高
            content: '<div style="padding: 20px;">' + display + '</div>'
        });
    },
    writeObj: function (obj) {
        var description = "";
        for (var i in obj) {
            var property = obj[i];
            description += i + " = " + property + ",";
        }
        layer.alert(description, {
            skin: 'layui-layer-molv',
            closeBtn: 0
        });
    },
    showInputTree: function (inputId, inputTreeContentId, leftOffset, rightOffset) {
        var onBodyDown = function (event) {
            if (!(event.target.id == "menuBtn" || event.target.id == inputTreeContentId || $(event.target).parents("#" + inputTreeContentId).length > 0)) {
                $("#" + inputTreeContentId).fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
            }
        };

        if (leftOffset == undefined && rightOffset == undefined) {
            var inputDiv = $("#" + inputId);
            var inputDivOffset = $("#" + inputId).offset();
            $("#" + inputTreeContentId).css({
                left: inputDivOffset.left + "px",
                top: inputDivOffset.top + inputDiv.outerHeight() + "px"
            }).slideDown("fast");
        } else {
            $("#" + inputTreeContentId).css({
                left: leftOffset + "px",
                top: rightOffset + "px"
            }).slideDown("fast");
        }

        $("body").bind("mousedown", onBodyDown);
    },
    baseAjax: function (url, tip) {
        var ajax = new $ax(Feng.ctxPath + url, function (data) {
            Feng.success(tip + "成功!");
        }, function (data) {
            Feng.error(tip + "失败!" + data.responseJSON.message + "!");
        });
        return ajax;
    },
    changeAjax: function (url) {
        return Feng.baseAjax(url, "修改");
    },
    zTreeCheckedNodes: function (zTreeId) {
        var zTree = $.fn.zTree.getZTreeObj(zTreeId);
        var nodes = zTree.getCheckedNodes();
        var ids = "";
        for (var i = 0, l = nodes.length; i < l; i++) {
            ids += "," + nodes[i].id;
        }
        return ids.substring(1);
    },
    eventParseObject: function (event) {//获取点击事件的源对象
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        return $(obj);
    },
    sessionTimeoutRegistry: function () {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                //通过XMLHttpRequest取得响应头，sessionstatus，
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    //如果超时就处理 ，指定要跳转的页面
                    window.location = Feng.ctxPath + "/global/sessionError";
                }
            }
        });
    },
    initValidator: function (formId, fields) {
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: fields,
            live: 'enabled',
            message: '该字段不能为空'
        });
    },
    initValidatorTip: function (formId, fields) {
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            container: 'tooltip',
            group:'.rowGroup',
            fields:fields,
            live: 'enabled',
            message: '该字段不能为空'
        }).on('error.field.bv', function(e, data) {
            var $parent = data.element.parents('.form-group-sm'),
                $icon   = $parent.find('.form-control-feedback[data-bv-icon-for="' + data.field + '"]'),
                title   = $icon.data('bs.tooltip').getTitle();
            $icon.tooltip('destroy').tooltip({
                html: true,
                placement: 'right',
                title: title,
                container: 'body'
            });
        });
    },
    underLineToCamel: function (str) {
        var strArr = str.split('_');
        for (var i = 1; i < strArr.length; i++) {
            strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].substring(1);
        }
        var result = strArr.join('');
        return result.charAt(0).toUpperCase() + result.substring(1);
    },
    randomNum: function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },
    newCrontab: function (href, menuName) {
        var dataUrl = href;
        var needCreateCrontab = true;

        // 轮询已有的标签，判断是否已经存在标签
        parent.$('.J_menuTab').each(function () {
            if ($(this).data('id') == dataUrl) {
                if (!$(this).hasClass('active')) {
                    $(this).addClass('active').siblings('.J_menuTab').removeClass('active');
                    parent.MyCrontab.scrollToTab(this);
                    parent.MyCrontab.$('.J_mainContent .J_iframe').each(function () {
                        if ($(this).data('id') == dataUrl) {
                            $(this).show().siblings('.J_iframe').hide();
                            $(this).attr('src', $(this).attr('src'));
                            return false;
                        }
                    });
                }
                needCreateCrontab = false;
                return false;
            }
        });

        //创建标签
        if (needCreateCrontab) {
            var tabLink = '<a href="javascript:;" class="active J_menuTab" data-id="' + dataUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
            parent.$('.J_menuTab').removeClass('active');
            parent.$('.J_menuTabs .page-tabs-content').append(tabLink);

            var iframeContent = '<iframe class="J_iframe" name="iframe' + Feng.randomNum(100,999) + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" seamless></iframe>';
            parent.$('.J_mainContent').find('iframe.J_iframe').hide().parents('.J_mainContent').append(iframeContent);
            parent.MyCrontab.scrollToTab($('.J_menuTab.active'));
        }
    },
    endWith: function(str, val){
    	if (str==null || val==null) {
    		return false;
    	}
    	if (str.length < val.length) {
    		return false;
    	}
        var temp = str.substring(str.length - val.length);
        if(temp == val){
        	return true;
        }else{
        	return false;
        }
    },
    setUrlParam: function(url, jsonObj){
    	for(var temp in jsonObj){
    		var key = temp;
    		var value = jsonObj[temp];
    		if (value!=null && value!='') {
    			if (url.indexOf("?")!=-1) {
    				url = url + "&" + key + "=" + encodeURI(encodeURI(value));
    			} else {
    				url = url + "?" + key + "=" + encodeURI(encodeURI(value));
    			}
    		}
    	}
    	return url
    },
    getUrlValue : 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;
    },
    addAjaxSelect: function (val) {
        var id = val.id;                                                            //下拉框对象的id
        var obj = val.obj;
        var url = val.url;                                                          //请求地址
        var displayCode = val.displayCode;                                          //下拉框实际值名称
        var displayName = val.displayName;                                          //下拉框显示值名称
        var bindData = val.bindData;
        var type = val.type;                                                        //请求方式 GET 或者 POST， 默认POST
        var async = val.async;                                                      //同步方式 {异步--falae, 同步--true}, 默认为同步
        if (async == null){
            async = false;
        }
        if (type==null){
            type == "POST";
        }
        var select = typeof id !="undefined"?$("#"+id):$(obj);
        select.empty();
        var ajax = new $ax(url, function(data){
            var length = data.length;
            var html = "<option value=''>---请选择---</option>";
            for(var i=0; i<length; i++){
                if (length == 1){
                    if(typeof bindData !="undefined" && bindData){
                        html = html+  "<option value=\""+data[i][displayCode]+"\" data-"+bindData+"=\""+data[i][bindData]+"\">"+data[i][displayName]+"</option>";
                    }else{
                        html = html+  "<option value=\""+data[i][displayCode]+"\">"+data[i][displayName]+"</option>";
                    }
                }else{
                    if(typeof bindData !="undefined" && bindData){
                	if(data[i][displayCode]==select.attr("defval")){
                        html += "<option selected='selected' value=\""+data[i][displayCode]+"\" data-"+bindData+"=\""+data[i][bindData]+"\">"+data[i][displayName]+"</option>";
                	}else{
                		html += "<option value=\""+data[i][displayCode]+"\" data-"+bindData+"=\""+data[i][bindData]+"\">"+data[i][displayName]+"</option>";
                	}
                    }else{
                	if(data[i][displayCode]==select.attr("defval")){
                        html += "<option selected='selected' value=\""+data[i][displayCode]+"\">"+data[i][displayName]+"</option>";
                	}else{
                		html += "<option value=\""+data[i][displayCode]+"\">"+data[i][displayName]+"</option>";
                	}
                    }
                }
            }
            select.append(html);
            if (length == 1){                                                       //如果只有一个选项，需要触发select的onchange方法
            	select.change();
            }
        },function(data){
            Feng.error("操作失败!");
        });
        ajax.async = async;
        ajax.type = type;
        ajax.set({});
        ajax.start();
    },
    acceptImg:function (){
        return {
            title : 'Images',
            extensions : 'gif,jpg,jpeg,bmp,png',
            mimeTypes : 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
        };
    },
    acceptWord:function (){
        return  {
            title: 'word',
            extensions: 'rar,zip,doc,xls,docx,xlsx,pdf',
            mimeTypes: '.rar,.zip,.doc,.xls,.docx,.xlsx,.pdf'
        };
    },
    acceptWord_Img:function (){
        return  {
            title: 'word_img',
            extensions: 'doc,xls,docx,xlsx,pdf,gif,jpg,jpeg,bmp,png',
            mimeTypes: '.doc,.xls,.docx,.xlsx,.pdf,image/gif,image/jpg,image/jpeg,image/bmp,image/png'
        };
    },
    resetSelect: function(id){
        var options = $("#"+id).children();
        if (options.length > 1){
            $("#"+id).val("");
        }
    },
    dictFormatter: function(code,type){
    	var result = "";
        var ajax = new $ax(Feng.ctxPath + "/dict/findDetailByCode/"+type+"/"+code, function(data){
        	result=data.name;
        },function(data){
            Feng.error("操作失败!");
        });
        ajax.start();
        return result;
    },
    showImg: function(context) {                                        //传一个<img>对像
    	var pic = $(context);
    	var src = pic.attr("src");
    	var sbp = window.top.$("#showBigPic");
    	sbp.empty();
    	sbp.append("<img id=\"_pic0001\" src=\""+src+"\" style=\"width:1px; height:1px; margin:0px;padding:0px;\"/>");
    	window.top.$("#_pic0001").viewer({
            toolbar:true,
            fullscreen:false
        });
        window.top.$("#_pic0001").click();
	},
    findChildDictBatch : function (data) {
        var ajax = new $ax(Feng.ctxPath + "/common/tool/findChildDictBatch", function (res) {
            var data = res.obj;
            for(var i in data){
                var html = "<option value=''>---请选择---</option>";
                for(var j in data[i]){
                    html =  html + '<option value="'+data[i][j].code+'">'+data[i][j].name+'</option>';
                }
                $("#"+i).empty().append(html);
            }
        }, function (data) {
            Feng.error("初始化失败!" + data.responseJSON.message + "!");
        });
        ajax.setData(data);
        ajax.setcontentType('application/json;charset=utf-8');
        ajax.start();
    },
    checkMobilePhoneNum: function(num) {
    	var telReg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    	if (!telReg.test(num)) {
    		return false;
    	} else {
    		return true;
    	}
	},
    getCheckLog : function (id,data) {
        //初始化日志
        $('#'+id).bootstrapTable({
            url: Feng.ctxPath + "/common/api/getCheckLog",
            method: 'POST',
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            search: false,					// 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
            showRefresh: false,				// 是否显示刷新按钮
            clickToSelect: true,			// 是否启用点击选中行
            singleSelect: true,				// 设置True 将禁止多选
            striped: true,  				// 是否显示行间隔色
            pagination: false,   			// 设置为 true 会在表格底部显示分页条
            paginationHAlign: "left",
            paginationDetailHAlign: "right",
            sidePagination: "server",   	// 设置在哪里进行分页，可选值为 'client' 或者 'server'
            showColumns: false,
            queryParams: function (params) {
                return data;
            },
            rowStyle : function(row,index){
                return {
                    css: {
                        "word-break": "break-word",
                        "white-space": "inherit"
                    }
                }
            },
            columns:
                [
                    {title: '步骤', field: 'stepName', visible: true, align: 'center', valign: 'middle',width:"10%",'class':'uitd_showTip',
                        formatter : function (value,row,index) {
                            return ""+value;
                        }
                    },
                    {title: '审核状态', field: 'stateName', visible: true, align: 'center', valign: 'middle',width:"10%",'class':'uitd_showTip'},
                    {title: '状态变更', field: 'stateChange', visible: true, align: 'center', valign: 'middle',width:"20%",'class':'uitd_showTip'},
                    {title: '审核意见/备注', field: 'description', visible: true, align: 'center', valign: 'middle',width:"30%",'class':'uitd_showTip',
                        formatter : function (value,row,index) {
                            return '<span data-toggle="tooltip" title="'+ value +'">"'+value+'"</span>';
                        }
                    },
                    {title: '操作人', field: 'createUser', visible: true, align: 'center', valign: 'middle',width:"15%",'class':'uitd_showTip'},
                    {title: '操作时间', field: 'createTime', visible: true, align: 'center', valign: 'middle',width:"15%",'class':'uitd_showTip'},
                ]
            ,
            onPostBody: function () {
                $('#'+id+"td.uitd_showTip").bind("mouseover", function () {
                    var htm = $(this).html();
                    $(this).webuiPopover({title: '详情', content: htm, trigger: 'hover'}).webuiPopover('show');
                });
            }
        });

    },
    getCheckLogModel : function (id,type,fileType) {
        layer.open({
            type: 1,
            title:"日志",
            fixed:false,
            content: '<table id="'+id+'"></table>',
            area: ['80%', '80%'],
            maxmin: true,
            success :function (layero, index) {
                //初始化日志
                $('#'+id).bootstrapTable({
                    url: Feng.ctxPath + "/api/talentInfo/getCheckLog",
                    method: 'POST',
                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    search: false,					// 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
                    showRefresh: false,				// 是否显示刷新按钮
                    clickToSelect: true,			// 是否启用点击选中行
                    singleSelect: true,				// 设置True 将禁止多选
                    striped: true,  				// 是否显示行间隔色
                    pagination: false,   			// 设置为 true 会在表格底部显示分页条
                    paginationHAlign: "left",
                    paginationDetailHAlign: "right",
                    sidePagination: "server",   	// 设置在哪里进行分页，可选值为 'client' 或者 'server'
                    showColumns: false,
                    queryParams: function (params) {
                        if(Feng.isEmptyStr(fileType)){
                            fileType = "";
                        }
                        return {"type":type,"mainId":id,"typeFileId":fileType,"active":1};
                    },
                    rowStyle : function(row,index){
                        return {
                            css: {
                                "word-break": "break-word",
                                "white-space": "inherit"
                            }
                        }
                    },
                    columns:
                        [
                            {title: '步骤', field: 'stepName', visible: true, align: 'center', valign: 'middle',width:"10%",'class':'uitd_showTip',
                                formatter : function (value,row,index) {
                                    return ""+value;
                                }
                            },
                            {title: '审核状态', field: 'stateName', visible: true, align: 'center', valign: 'middle',width:"10%",'class':'uitd_showTip'},
                            {title: '状态变更', field: 'stateChange', visible: true, align: 'center', valign: 'middle',width:"20%",'class':'uitd_showTip'},
                            {title: '审核意见/备注', field: 'description', visible: true, align: 'center', valign: 'middle',width:"30%",'class':'uitd_showTip',
                                formatter : function (value,row,index) {
                                    return '<span data-toggle="tooltip" title="'+ value +'">"'+value+'"</span>';
                                }
                            },
                            {title: '操作人', field: 'createUser', visible: true, align: 'center', valign: 'middle',width:"15%",'class':'uitd_showTip'},
                            {title: '操作时间', field: 'createTime', visible: true, align: 'center', valign: 'middle',width:"15%",'class':'uitd_showTip'},
                        ]
                    ,
                    onPostBody: function () {
                        $('#'+id+"td.uitd_showTip").bind("mouseover", function () {
                            var htm = $(this).html();
                            $(this).webuiPopover({title: '详情', content: htm, trigger: 'hover'}).webuiPopover('show');
                        });
                    }
                });
            }
        });
    },
    pdfReader:function(url,filename){
        filename = typeof filename == "undefined" ? "临时文件" : filename;
        var index = layer.open({
            type: 2,
            title: "查看PDF文件 - " + filename,
            area: ['80%', '80%'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: url
        });
        return index;
    },
    showPdf : function(url,id,title){
        if(Feng.isEmptyStr(id)){
            id = "id";
        }
        if(Feng.isEmptyStr(title)){
            title = "预览";
        }
        let origin = window.location.origin;
        //let full_url = "https://fileview.jinjianghc.com/onlinePreview?url=" + encodeURIComponent(Base64.encode(url));
        var index = layer.open({
            id:id,
            type: 2,
            shade: 0,
            title: title,
            area: ['80%', '80%'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: url,
        });
        // layer.full(index);
    },
    showExcel:function(url,id,title){
        window.location.href = url;
    },
    showFile:function(url,id,title){
        if(Feng.isEmptyStr(id)){
            id = "id";
        }
        if(Feng.isEmptyStr(title)){
            title = "预览";
        }
        var index = layer.open({
            id:id,
            type: 2,
            shade: 0,
            title: title,
            area: ['600px', '350px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: url,
        });
    },
    isEmptyStr:function(str) {
        if(str == null || str == ''){
            return true;
        }else{
            return false;
        }
    },
    isNotEmptyStr:function (str) {
        if(str!=null && str != ''){
            return true;
        }else{
            return false;
        }
    },
    checkAll:function (id) {
        $("#"+id+" input").each(function () {
            this.checked = true;
        })
    },
    unCheckAll :function(id) {
        $("#"+id+" input").each(function () {
            if(this.checked){
                this.checked = false;
            }else{
                this.checked = true;
            }
        })
    },
    showMiniFileModal:function (project,type,id) {
        layer.open({
            type: 2,
            title: "附件",
            shade: 0,
            resize:true,
            maxmin:true,
            // moveOut:true,
            id:"file",
            area: ['800px', '500px'],
            offset: 'rb', //右下角弹出content:
            shift: 2,
            content: Feng.ctxPath +  "/api/common/gotoFileShow",
            zIndex: layer.zIndex,
            success:function (layero,index) {
                layer.setTop(layero);
                //按钮【按钮一】的回调
                var iframeWin = window[layero.find('iframe')[0]['name']];
                iframeWin.getFile(project,type,id);
            }
        });
    },
    getCheckBoxValues:function (str) {              //获取checkbox值
        var val = "";
        $("#"+str+" input[name='"+str+"']").each(function () {
            if (this.checked) {
                val = val + $(this).val() + ",";
            }
        });
        return val.substring(0,val.length-1);
    },
    initDate:function () {
        $(".date").removeAttr('lay-key');
        $(".date").each(function(){
            laydate.render({
                elem: this
                ,type: 'date'
                ,trigger: 'click'
            });
        });
    },
    downloadFile:function (id,type) {
        window.location.href = Feng.ctxPath + "/common/api/downloadFile?id=" + id + "&type="+type;
    },
    bankChange:function (val,target){
        var bank = $("#"+val).val();
        if($.trim(bank)=='中国工商银行'){
            $("#"+target).val('102391050013');
        }else {
            $("#"+target).val('');
        }
    },
    chkFileInvalid:function(file,maxImageSize,maxFileSize,fileType,msg){
        var size = 0;
        if(typeof fileType != "undefined" && fileType != null){
            if(fileType.indexOf(file.type)<0){
                msg = typeof msg !="undefined"?msg:"不支持的文件类型";
                Feng.error(msg)
                return false;
            }
        }
        switch(file.type){
            case "image/jpeg":
            case "image/gif":
            case "image/png":
            case "image/jpg":
                size = maxImageSize * 1024 * 1024;//图片限制最大5M
                if(file.size > size){
                    Feng.error("图片大小不能超过"+maxImageSize+"MB!");
                    return false;
                }
                break;
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            case "application/pdf":
            case "application/msword":
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            case "application/vnd.ms-excel":
            case "application/zip":
            case "application/x-rar-compressed":
            case "application/x-7z-compressed":
                size = maxFileSize * 1024 * 1024;//其它允许文件类型限制最大均为10M
                if(file.size > size){
                    Feng.error("文件大小不能超过"+maxFileSize+"MB!");
                    return false;
                }
                break;
            default:
                Feng.error("文件类型不支持")
                return false;
        }
        return true;
    },
    isImg:function(type){        
        var imgtypes = ["image/jpeg", "image/gif", "image/png", "image/jpg"];
        if(imgtypes.indexOf(type) > -1){
            return true;
        }
        return false;
    }
};
