/**
 * 
 * @authors btoe.bt
 * @date    2018-03-16 15:15:01
 * @version v1.0
 */

//获取url参数   调用方法：$.getUrlParam('@Param');
(function($) {
    $.getUrlParam = function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
})(jQuery);


function send_json(url,content,fn,btn) { //参数：提交地址，form表单内容（json格式）,提交完成之前禁用的按钮
	if(btn==undefined){
		var that = $('#submit');
	}else{
		var that = $(btn);
	}
    that.attr('disabled', 'disabled');
	var waiting = parent.layer.load(0, { shade: false });
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        timeout: 18000,
        data: content,
        success: function(data) {
            parent.layer.close(waiting);
            parent.layer.msg(data.msg, { time: 1000 });
            that.removeAttr("disabled");
            if(fn!=undefined){
                   fn();
            }       
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (textStatus == "timeout") {
                parent.layer.close(waiting);
                parent.layer.msg('超时，请重新提交', { time: 3000 });
                that.removeAttr("disabled");
            } else {
                parent.layer.close(waiting);
                parent.layer.msg('提交失败，请重新提交！错误代码：' + textStatus, { time: 3000 });
                that.removeAttr("disabled");
            }
        }
    })
};


function get_json(url, fn, text) { //参数：提交地址，成功后执行的函数，自定义错误提示
	if(url.indexOf('tongji')<0){
		if(parent.layer!=undefined){
			var waiting = parent.layer.load(0, { shade: false });
		}else{
			var waiting = layer.load(0, { shade: false });
		}
	}
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'JSON',
        timeout: 8000,
        success: function(data) {
            if (data.code == 1) {
                fn(data);
                parent.layer.close(waiting);
                $('body').fadeIn(function(){
					if($('#wizard2').length!=0){
						bootstrapWizard();
					}
				});
            } else {
                parent.layer.close(waiting);
                parent.layer.msg(data.msg, { time: 3000 });
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (text != undefined) {
                parent.layer.close(waiting);
                parent.layer.msg(text, { time: 3000 });
            } else {
                parent.layer.close(waiting);
                parent.layer.msg('提加载失败，请重新尝试!错误代码：' + textStatus, { time: 3000 });
            }
        }
    })
};

//删除文章
function Delete(url) { //参数：提交地址(含有被删除文章id，可以是数组，支持批量删除)
    parent.layer.confirm('确定删除吗？', {
        btn: ['确定', '取消'] //按钮
    }, function() {
        get_json(url, function(data, waiting) { //删除成功后返回被删除id，可以是数组，支持批量删除
            for (var i = 0; i < data.data.length; i++) {
                $('.table tr[id="l' + data.data[i] + '"]').remove();
            }
            parent.layer.close(waiting);
            parent.layer.msg(data.msg, { time: 1000 });
        })
    }, function() {
        /* 点击取消执行的函数 */
    });
};

//表单不能为空
function noEmpty(fn) { //参数：如果必填项都有内容执行的方法（提交）
    var num = 0;
    $('#form input[data-no-empty="true"]').each(function(index, el) {
        var that = $(this);
        var val = that.val();
        if (val.length == 0) {
            that.parents('.form-group').addClass('has-error');
            num++;
        } else {
            that.parents('.form-group').removeClass('has-error');
        }
    });
    if (num == 0) {
        fn();
    } else {
        parent.layer.msg('请填写完整红框内的信息！', { time: 1000 });
    }
};

//分页
function pages(data) { //参数：含有页码信息的json
    var pagecur = data.data.page;
    var pageall = data.data.pageall;
    var page = Math.ceil(pageall / 15);
    var pagelist = '';
    for (var i = 1; i <= page; i++) {
        if (i == pagecur) {
            pagelist += '<li class="disabled active"><span>' + i + '</span></li>';
        } else {
            pagelist += '<li><span>' + i + '</span></li>'
        }
    }
    $('#page-list').html(pagelist);
    $('#pageall span').html('共' + pageall + '条');
    if (pagecur <= 1) {
        $('#pageprev').addClass('disabled')
    }else {
		$('#pageprev').removeClass('disabled')
	}
    if (pagecur >= page) {
        $('#pagenext').addClass('disabled')
    }else {
		$('#pagenext').removeClass('disabled')
	}
};

//更改排序
function changeSort(url) {
    var that = $(this);
    var id = that.parent().parent().find('label').text();
    var val = that.val();
    get_json(url, function() {
        console.log("1")
    })
};

//全选与反选
$(function() {
    $('#selectAll').on('click', function() {
        var that = $(this);
        var stat = that.attr('data-checked');
        if (stat == 1) {
            $('.table .checkbox-custom input:checkbox').prop('checked', false);
            that.html('<i class="fa  fa-check-square-o"></i>全选');
            that.attr('data-checked', 0);
        } else {
            $('.table .checkbox-custom input:checkbox').prop('checked', true);
            that.html('<i class="fa fa-ban"></i>取消');
            that.attr('data-checked', 1);
        }
    });
    $('#selectback').on('click', function() {
        var that = $(this);
        var stat = that.attr('data-checked');
        if (stat == 1) {
            $('.table .checkbox-custom input:checkbox').prop('checked', false);
            that.html('<i class="fa fa-check-square"></i>反选');
            that.attr('data-checked', 0);
        } else {
            $('.table .checkbox-custom input:checkbox').each(function() {
                this.checked = !this.checked;
            });
            that.html('<i class="fa fa-ban"></i>取消');
            that.attr('data-checked', 1);
        }
    })
});

//移动栏目
function moveMenu(menuId, curpage) { //参数：目标栏目ID，当前页码
    var articleId = [];
    var oldcatid = $.getUrlParam('catid');
    get_select(articleId);
	if(articleId.length!=0){
		get_json('../../api/content.ashx?action=moveid&oldcatid=' + oldcatid + '&catid=' + menuId + '&id=' + articleId + '&page=' + curpage, function(data) {
			pages(data);
			getlist(data);
			parent.layer.msg('操作成功！' , { time: 1000 });
		},'移动栏目失败，请重试！')
	}else{
		parent.layer.msg('没有选中的栏目！' , { time: 3000 });
	}

};

//批量删除
function batchDelete(url) {
    var articleId = [];
    get_select(articleId);
	if(articleId.length!=0){
		Delete(url + articleId);
	}else{
		parent.layer.msg('没有选中的栏目！' , { time: 3000 });
	}

};

//获取选中
function get_select(articleId) { //获取列表内被复选框选中的条目，参数是被选中栏目的id（数组）
    $('.table input:checkbox').each(function(index, el) {
        var that = $(this);
        if (that.is(':checked')) {
            var val = that.val();
            articleId.push(val)
        }
    });
};

//时间戳转换
function formatTime(val, gs) { //参数：val =/Date(1522391264397)/
    var a = val.replace("/Date(", "").replace(")/", "");
    var re = /-?\d+/;
    var m = re.exec(a);
    var d = new Date(parseInt(m[0]));
    // 按【yyyy-MM-dd hh:mm:ss】的格式返回日期
    return d.format(gs);
};

// 用于格式化日期显示
Date.prototype.format = function(format) //author: meizz 
    {
        var o = {
            "M+": this.getMonth() + 1, //month 
            "d+": this.getDate(), //day 
            "h+": this.getHours(), //hour 
            "m+": this.getMinutes(), //minute 
            "s+": this.getSeconds(), //second 
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
            "S": this.getMilliseconds() //millisecond 
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }

//提示工具
$(function() {
	if($("[data-toggle='tooltip']").length>0){
		$("[data-toggle='tooltip']").tooltip();
	}
    if($("[data-toggle='popover']").length>0){
		$("[data-toggle='popover']").popover({
			trigger: 'hover', //触发方式
			html: true, // 为true的话，data-content里就能放html代码了
			content: function(){
			var src = $(this).val();
			var content = '<img src="'+src+'" width="248">';
			   return content
			} //这里可以直接写字符串，也可以 是一个函数，该函数返回一个字符串；
		});
	}

});
