var layer;
var element;
var form;
var laypage;
var laydate;
var xmSelect;

// 使用layui内部jQuery
var $ = layui.$;
var jQuery = layui.$;

$(function() {

	// layer变量
	layer = layui.layer;
	element = layui.element;
	form = layui.form;
	laypage = layui.laypage;

	// 执行一个laypage实例
	laypage.render({
		elem: 'pageInfo', // 渲染节点
		count: page.total, // 总记录数
		curr: page.pageNum, // 起始页
		limit: page.pageSize, // 每页记录数
		limits: [10, 20, 50, 100, 200], // 显示分页数
		layout: ['count', 'prev', 'page', 'next', 'skip', 'limit'],
		jump: function(obj, first) {
			// 首次不执行
			if (!first) {
				// do something
				$("input[name='pageNum']").val(obj.curr);
				$("input[name='pageSize']").val(obj.limit);
				$("#searchForm").submit();
			}
		}
	});


	// 多选组件
	layui.config({
		base: ctx + 'lib/layui/exts/xmSelect/'
	}).extend({
		xmSelect: 'xm-select'
	}).use(['xmSelect'], function() {
		xmSelect = layui.xmSelect;

		if (typeof initXmSelect != "undefined") {
			initXmSelect();
		}
	})


	// 日期控件
	layui.use('laydate', function() {
		laydate = layui.laydate;

		// 执行laydate实例
		$(".laydate").each(function() {
			$(this).attr("id", "date_" + guid());
			$(this).attr("readonly", true);

			laydate.render({
				elem: "#" + $(this).attr("id"), // 指定元素
				type: 'date',
				trigger: 'click',
				format: 'yyyy-MM-dd' // 可任意组合
			});
		})

		$(".laytime").each(function() {
			$(this).attr("id", "time_" + guid());
			$(this).attr("readonly", true);

			laydate.render({
				elem: "#" + $(this).attr("id"), // 指定元素
				type: 'datetime',
				trigger: 'click',
				format: 'yyyy-MM-dd HH:mm:ss' // 可任意组合
			});
		})
	});
	
	// 设置input[type='number']为正整数
	$("input[type='number']").attr("lay-affix", "number");
	$("input[type='number']").attr("lay-precision", 0); // 取整
	$("input[type='number']").attr("min", 0);
	$("input[type='number']").attr("max", 1000000);
	$("input[type='number']").attr("step", 1); // 步进为1
	
	$("input.money").attr("lay-precision", 2); //小数进度为2
	$("input.money").attr("step", 0.01); // 步进为0.01

	form.render();

	// 关闭input自动填充
	$("input").attr("autocomplete", "off");

	// 菜单选中
	var url = location.pathname.replace(/\//g, "/") + "?";
	$("a[href*='" + url + "']:first").parent().addClass("layui-this");

	// 只显示当前大类菜单
	$("a[href*='" + url + "']").parent().parent().parent().addClass("layui-nav-itemed");
		
	// 翻译按钮隐藏
	$("#translate").hide();
})

// 关闭AJAX相应的缓存
$.ajaxSetup({
	cache: false
});


// 退出登录
function loginOut() {
	if (confirm("是否退出登录?")) {
		location.href = ctx + "loginOut";
	}
}

// 日期格式化
Date.prototype.format = function(format) {
	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"H+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '')
			.substr(4 - RegExp.$1.length));
	}
	for (var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k]
				: ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}

function formatDate(now) {
	if (now == null || now == '') {
		return "";
	}

	return new Date(now).format("yyyy-MM-dd HH:mm:ss");
}

// 查看图片
function seePic(url) {
	window.open(url);
}

// 生成uuid
function S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4()
		+ S4() + S4());
}

// 时间字符串转时间戳
function strToTime(str) {
	var str = str.replace(/-/g, '/');
	var timestamp = new Date(str).getTime();

	return timestamp
}

// 获取url参数
function getQueryString(name) {
	/*
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null)
		return unescape(r[2]);
	return null;
	*/
	const paramsStr = window.location.search;
	const params = new URLSearchParams(paramsStr);
	return params.get(name); // list
}

// 下载文件
function downloadFile(url, name) {
	window.open(ctx + "downloadFile?url=" + encodeURIComponent(url) + "&name="
		+ encodeURIComponent(name));
}

// form转json
function form2JsonString(formId) {
	var paramArray = $('#' + formId).serializeArray();
	/* 请求参数转json对象 */
	var jsonObj = {};
	$(paramArray).each(function() {
		jsonObj[this.name] = this.value;
	});
	return JSON.stringify(jsonObj);

}

function changeLang() {
	$.ajax({
		type: 'POST',
		url: ctx + 'main/changeLang',
		data: $("#adminForm").serialize(),
		dataType: 'json',
		success: function(data) {
			if (data.success) {
				location.reload();
			} else {
				layer.msg(data.msg);
			}
		},
		error: function() {
			layer.alert("请求失败，请刷新重试");
		}
	});
}


function setParamOrder(id, seq) {
	if (seq == -1) {
		// 前移
		var prev = $("#" + id).prev();
		$("#" + id).after(prev);
	} else {
		// 后移
		var next = $("#" + id).next();
		$("#" + id).before(next);
	}
}

// 显示载入框
var loadIndex;
function showLoad() {
	loadIndex = layer.load();
}
function closeLoad() {
	layer.close(loadIndex);
}


function userCenter() {
	location.href = ctx + "userPage/userCenter";
}

function adminCenter(group) {
	location.href = ctx + "adminPage/adminCenter?group=" + group;
}


function showTgBind() {
	layer.alert("在任意聊天窗口发送“@freecdnBot”然后点击这条消息即可打开与freecdnBot的聊天，发送任意消息给freecdnBot它会返回你的信息，其中包含一个ID，这就是我们需要的chat_id");
}

function goUser(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/user?pageSize=20&id=" + id;
	}
}

function goOrder(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/orderAdmin?pageSize=20&id=" + id;
	} else {
		location.href = ctx + "userPage/order?pageSize=20&id=" + id;
	}
}

function goMachineOrder(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/machineOrderAdmin?pageSize=20&id=" + id;
	} else {
		location.href = ctx + "userPage/machineOrder?pageSize=20&id=" + id;
	}
}

function goMachine(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/machine?pageSize=20&id=" + id;
	}
}
function goMachineVps(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/machineVps?pageSize=20&id=" + id;
	}
}

function goDomain(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/domainAdmin?pageSize=20&id=" + id;
	} else {
		location.href = ctx + "userPage/domain?pageSize=20&id=" + id;
	}
}

function goDomainOrder(orderId) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/domainAdmin?pageSize=20&orderId=" + orderId;
	} else {
		location.href = ctx + "userPage/domain?pageSize=20&orderId=" + orderId;
	}
}

function goUpstreamOrder(orderId) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/upstreamAdmin?pageSize=20&orderId=" + orderId;
	} else {
		location.href = ctx + "userPage/upstream?pageSize=20&orderId=" + orderId;
	}
}

function goCertOrder(orderId) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/certAdmin?pageSize=20&orderId=" + orderId;
	} else {
		location.href = ctx + "userPage/cert?pageSize=20&orderId=" + orderId;
	}
}

function goProduct(id) {
	if (location.href.indexOf("adminPage") > -1) {
		location.href = ctx + "adminPage/product?pageSize=20&id=" + id;
	}
}