var isgetdata = $('#isgetdata').val();
var biz = $('#biz').val() || 'cloud';
var pagesize = 30;
var page = 1;
var _protocol = new Array();

$(document).ready(function() {
	if(isgetdata == 1){
		get_list(page,pagesize);
	}
	$('#page').change(function(){
		page = $('#page').val();
		get_list(page,pagesize);
	});

	frame_type();
	var cid_name = $("#cid").attr("cid_name");
	$("#cid option[value='"+cid_name+"']").attr("selected", true);
});
function get_list_protocol(type,is=false){
	if($.inArray(type, _protocol) >= 0 && is==false){
		return false;
	}
	_protocol.push(type);
	showLoading();
	$.ajax({
		type : 'GET',
		url : 'ajax.php?act=get_protocol&type='+type,
		dataType : 'json',
		success : function(data) {
			hideLoading();
			$("#list_protocol"+type).empty();
			$.each(data, function(i,v){
				var tmp = '<tr class="hover:bg-gray-50" id="row_p'+v.id+'">' +
				'<td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap"><div class="flex items-center gap-1"><a class="text-blue-600 hover:text-blue-800 cursor-pointer" onclick="protocol_sort_show(\''+v.cid+'\')"><i class="fa fa-sort" id="sort_icon_p'+v.id+'"></i></a><span id="sort_text_p'+v.id+'">'+v.sort+'</span><input type="hidden" name="sort_p['+v.id+']" value="'+v.sort+'"></div></td>' +
						'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+(v.is==1?'<font color="red">'+v.cid+'</font>':v.cid)+'</td>' +
						'<td class="px-4 py-3 whitespace-nowrap" style="min-width:100px;"><input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" value="'+v.name+'" name="name['+v.id+']" placeholder="协议名称" required></td>' +
						'<td class="px-4 py-3 whitespace-nowrap" style="min-width:50px;"><input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" value="'+(v.type==null?'':v.type)+'" name="type['+v.id+']" placeholder="协议ID" required></td>' +
						'<td class="px-4 py-3 whitespace-nowrap" style="min-width:60px;"><select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm text-gray-700" name="is_pwd['+v.id+']" default="'+v.is_pwd+'"><option value="1">密码+扫码</option><option value="2">密码登录</option><option value="0">扫码登录</option></select></td>' +
						'<td class="px-4 py-3 whitespace-nowrap"><input type="checkbox" name="status['+v.id+']"'+(v.status==1?' checked':'')+'></td>' +
						'<td class="px-4 py-3 whitespace-nowrap"><button type="button" class="px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-xs rounded-lg transition whitespace-nowrap" onclick="del_p('+v.id+')">删除</button></td>' +
						'</tr>';
				$('#list_protocol'+v.cid).append(tmp);
			});
			tmp = '<tr class="hover:bg-gray-50">' +
				'<td class="px-4 py-3 whitespace-nowrap">新增</td>' +
				'<td class="px-4 py-3 whitespace-nowrap">&nbsp;</td>' +
				'<td class="px-4 py-3 whitespace-nowrap" style="min-width:100px;"><input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" id="name'+type+'" placeholder="填写协议名称"></td>' +
						'<td class="px-4 py-3 whitespace-nowrap" style="min-width:50px;"><input type="number" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" id="cid'+type+'" placeholder="填写协议ID"></td>' +
						'<td class="px-4 py-3 whitespace-nowrap" style="min-width:80px;"><button type="button" class="px-3 py-1 bg-green-500 hover:bg-green-600 text-white text-xs rounded-lg transition whitespace-nowrap" onclick="add_protocol(\''+type+'\')">添加</button></td>' +
				'<td class="px-4 py-3 whitespace-nowrap">&nbsp;</td>' +
				'<td class="px-4 py-3 whitespace-nowrap">&nbsp;</td>' +
				'</tr>';
			$("#list_protocol"+type).append(tmp);
			select_default();
		}
	});
}
function add_protocol(k){
	var name = $('#name'+k).val();
	var type = $('#cid'+k).val();
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=add_protocol&cid='+k,
		data : {name:name,type:type},
		dataType : 'json',
		success : function(data){
			hideLoading();
			showToast(data.msg, 'success');
			get_list_protocol(k,true);
		}
	});
}
function protocol_sort_show(type){
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=protocol_sort',
		data : {type:type},
		dataType : 'json',
		success : function(data){
			hideLoading();
			var tmp = '<div class="mb-4 text-sm text-red-600 font-medium">越少越靠前</div>';
			$.each(data, function(i,v){
				tmp += '<div class="mb-3">' +
						'<label class="block text-sm font-medium text-gray-700 mb-1">'+v.name+'</label>' +
						'<input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all" name="sort['+v.id+']" value="'+v.sort+'">' +
						'</div>';
			});
			$('#protocol_con').empty();
			$('#protocol_con').html('<input type="hidden" name="frame_type" value="'+type+'">'+tmp);
			document.getElementById('protocol_sort').classList.remove('hidden');
			document.getElementById('protocol_sort').classList.add('flex');
		}
	});
}
function edit_protocol_sort() {
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=edit_protocol_sort',
		data : $('#protocol_con').serialize(),
		dataType : 'json',
		success : function(data){
			hideLoading();
			showToast(data.msg, 'success');
			document.getElementById('protocol_sort').classList.add('hidden');
			document.getElementById('protocol_sort').classList.remove('flex');
			var frameType = $('#protocol_con input[name="frame_type"]').val();
			if(frameType){
				get_list_protocol(frameType, true);
			}
		}
	});
}
function saveOrder2() {
	var i=1;
	$("#list_protocol tr").each(function(){
		var cid = $(this).attr('data-protocol');
		$("input[name='sort_p["+cid+"]']").val(i++);
	});
}
function get_list(page,pagesize){
	var kw = $("input[name='kw']").val();
	var type = $("select[name='type']").val();
	showLoading();
	$.ajax({
		type : 'POST',
		data : {pagesize:pagesize,page:page,kw:kw,type:type,biz:biz},
		url : 'ajax.php?act=get_loginapi',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			adddata(data.data,data.class);
			$('#total').html(data.total);
			var totalPage = Math.ceil(data.total / pagesize);
			if(totalPage >= 1){
				$('#page').html('');
				for(var i = 1; i <= totalPage; i++){
				    $('#page').append('<option value="'+ i +'">' + i + '</option>');
				}
				$('#page').val(page);
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
function adddata(data,classData){
	$("#list").empty();
	var classOptions = {};
	$.each(classData, function(i,v){
		var cbiz = v.biz || 'cloud';
		if(!classOptions[cbiz]) classOptions[cbiz] = '<option value="0">未分类</option>';
		classOptions[cbiz] += '<option value="'+v.id+'">'+v.name+'</option>';
	});

	$.each(data, function(i,v){
		var rowBiz = v.biz || biz || 'cloud';
		var option = classOptions[rowBiz] || '<option value="0">未分类</option>';
		var bizBadge = rowBiz == 'dg'
			? '<span class="inline-flex px-2.5 py-1 text-xs rounded-full bg-indigo-50 text-indigo-700 border border-indigo-100 whitespace-nowrap">代挂</span>'
			: '<span class="inline-flex px-2.5 py-1 text-xs rounded-full bg-sky-50 text-sky-700 border border-sky-100 whitespace-nowrap">云端</span>';
		var tmp = '<tr class="hover:bg-gray-50" data-cid="'+v.id+'">' +
			'<td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap"><div class="flex items-center gap-1"><a class="text-blue-600 hover:text-blue-800 cursor-pointer sort_drag" onclick="api_sort('+v.id+','+v.sort+')"><i class="fa fa-sort" id="sort_icon_'+v.id+'"></i></a><span id="sort_text_'+v.id+'">'+v.sort+'</span><input type="hidden" name="sort['+v.id+']" value="'+v.sort+'"></div></td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+v.id+' '+bizBadge+(v.apipwd!=''?' <font color="green">免费</font>':'')+'</td>' +
			'<td class="px-4 py-3 whitespace-nowrap"><a onclick="shop_path(\''+v.path+'\')">'+v.citybz+'</a></td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap"><span>'+v.type+status_api(v.id,v.status_api,v.status)+'</span></td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap"><span>'+v.url+'</span></td>' +
			'<td class="px-4 py-3 whitespace-nowrap" style="min-width:150px;"><select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm text-gray-700" id="class'+v.id+'" onchange="javascript:edit_login_class_id(\''+v.id+'\',this.value)">'+option+'</select></td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+v.max+'</td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">'+v.online_census+'</td>' +
			'<td class="px-4 py-3 whitespace-nowrap">'+show_online_census(v.id,v.show_online_census)+'</td>' +
			'<td class="px-4 py-3 whitespace-nowrap">'+status(v.id,v.status)+'</td>' +
			'<td class="px-4 py-3 whitespace-nowrap"><a href="./qqlist.php?kw='+v.id+'&type=2&biz='+encodeURIComponent(rowBiz)+'" class="px-3 py-1 bg-green-500 hover:bg-green-600 text-white text-xs rounded-lg transition whitespace-nowrap">QQ列表</a>&nbsp;<a href="?my=edit&id='+v.id+'" class="px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white text-xs rounded-lg transition whitespace-nowrap">编辑</a>&nbsp;<button type="button" onclick="del_loginapi('+v.id+')" class="px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-xs rounded-lg transition whitespace-nowrap">删除</button>&nbsp;<button type="button" onclick="del_frame_qq('+v.id+')" class="px-3 py-1 bg-gray-500 hover:bg-gray-600 text-white text-xs rounded-lg transition whitespace-nowrap">操作</button></td>' +
			'</tr>';
	    $("#list").append(tmp);
	    $("#class"+v.id).val(v.cids);
	});
	select_default();
}
function edit_login_class_id(id,cids,type=''){
	$.post('ajax.php?act=edit_login_class_id', {id:id,cids:cids,type:type}, function(d, textStatus, xhr) {
		if(d.code == 1){
			showToast(d.msg, 'success');
		}else{
			showToast(d.msg, 'error');
		}
	},'json');
}
function shop_path(path){
	showToast('框架路径: ' + path, 'info');
}
function api_sort(id,sort) {
	var text = prompt('排序操作\n当前序号：'+sort+'\n序号越小越靠前\n请输入新序号：');
	if(text !== null) {
		showToast('正在操作中...', 'info');
		$.post('ajax.php?act=api_sort', {id:id,sort:text}, function(d, textStatus, xhr) {
			if(d.code == 1){
				showToast(d.msg, 'success');
				get_list(page,pagesize);
			}else{
				showToast(d.msg, 'error');
			}
		},'json');
	}
}
function saveOrder() {
	var i=1;
	$("#list tr").each(function(){
		var cid = $(this).attr('data-cid');
		$("input[name='sort["+cid+"]']").val(i++);
	});
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=set_loginapi',
		data : $('#form_data').serialize()+'&type=sort',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, 'success');
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
function status_api(id,zt,status){
	if(status == 1){
		if(zt == 0){
			return '<font color="red">异常</font>';
		}else{
			return '';
		}
	}else{
		return '';
	}
}
function status(id,zt){
	if(zt == 1){
		return '<button type="button" onclick="set_status(\'status\','+id+',0)" class="px-2 py-1 bg-green-500 hover:bg-green-600 text-white text-xs rounded-lg transition">开启中</button>';
	}else{
		return '<button type="button" onclick="set_status(\'status\','+id+',1)" class="px-2 py-1 bg-red-500 hover:bg-red-600 text-white text-xs rounded-lg transition">已关闭</button>';
	}
}
function show_online_census(id,zt){
	if(zt == 1){
		return '<button type="button" onclick="set_status(\'census\','+id+',0)" class="px-2 py-1 bg-green-500 hover:bg-green-600 text-white text-xs rounded-lg transition">显示</button>';
	}else{
		return '<button type="button" onclick="set_status(\'census\','+id+',1)" class="px-2 py-1 bg-red-500 hover:bg-red-600 text-white text-xs rounded-lg transition">不显示</button>';
	}
}
function set_status(type,id,zt){
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=set_loginapi',
		data : {type:type,id:id,zt:zt},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, data.code == 1 ? 'success' : 'error');
			if(data.code == 1){
				get_list(page,pagesize);
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
function saveSetting(obj,type='add_loginapi'){

	//showToast(decodeURI($(obj).serialize()), 'info');
	//return false;

	if(type == 'custom_protocol' && $('input[name="protocol_name"]').val() == ''){
		showToast('名称不能为空', 'error');
		return false;
	}
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act='+type,
		data : $(obj).serialize(),
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, data.code == 1 ? 'success' : 'error');
			if(type == 'custom_protocol' && data.code == 1){
				location.reload();
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
var is_cid = false;
function frame_type(){
	var type = $('select[name="type"]').val();
	var $protoRow = $('#protocol_row');
	var $cidSelect = $('select[name="cid"]');
	if ($protoRow.length) {
		if (type === 'myqq' || type === 'dr') {
			if ($cidSelect.find('option[value=""]').length === 0) {
				$cidSelect.prepend('<option value="">MyQQ/DR无需选择</option>');
			}
			$cidSelect.val('');
			$protoRow.addClass('hidden');
		} else {
			$cidSelect.find('option[value=""]').remove();
			$protoRow.removeClass('hidden');
		}
	}
	select_default();
}
select_default();
function select_default(){
	var items = $("select[default]");
	for (i = 0; i < items.length; i++) {
		$(items[i]).val($(items[i]).attr("default")||0);
	}
}
var current_del_frame_id = null;
var current_del_loginapi_id = null;

function del_frame_qq(id){
	current_del_frame_id = id;
	$('#del_frame_qq_confirm').val('');
	$('#del_frame_qq_modal').modal('show');
}

function confirm_del_frame_qq(){
	var text = $('#del_frame_qq_confirm').val();
	if(text != '确认删除'){
		showToast('如需删除，请输入 确认删除 ', 'error');
		return false;
	}
	if(current_del_frame_id === null){
		showToast('参数错误', 'error');
		return false;
	}
	$('#del_frame_qq_modal').modal('hide');
	showToast('正在操作中...', 'info');
	$.post('ajax.php?act=del_frame_qq', {id:current_del_frame_id}, function(d, textStatus, xhr) {
		if(d.code == 1){
			showToast(d.msg, 'success');
		}else{
			showToast(d.msg, 'error');
		}
		current_del_frame_id = null;
	},'json');
}

function del_loginapi(id){
	current_del_loginapi_id = id;
	$('#del_loginapi_modal').modal('show');
}

function confirm_del_loginapi(){
	if(current_del_loginapi_id === null){
		showToast('参数错误', 'error');
		return false;
	}
	$('#del_loginapi_modal').modal('hide');
	showToast('正在操作中...', 'info');
	set_status('del',current_del_loginapi_id,0);
	current_del_loginapi_id = null;
}
function check_api(){
	let url = $("input[name='url']").val();
	if(url == ''){
		showToast('请输入登录API，格式如下\n框架服务器ip:端口号\n例：http://127.0.0.1:8886\n把【127.0.0.1】和【8886】修改成自己的', 'error');
		return false;
	}
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=check_api',
		data : {url:url},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			var ok = data.retcode == 200 || data.code == 0 || data.msg == 'ok' || (data.bot && data.bot.list);
			if(!ok && data.retcode == 300 && data.msg && data.msg.indexOf('添加失败') !== -1){
				ok = true;
			}
			if(ok){
				showToast('通讯正常', 'success');
			}else{
				let tmp = '通讯失败，大概原因如下\n' +
					'1、检查 端口 是否放行\n' +
					'2、框架服务器是否有外网ip\n' +
					'3、大部分的挂机宝是没有外网ip的(不可使用)\n' +
					'4、端口号放行后，还是通讯失败的请重启框架服务器\n' +
					'5、登录API必须是http://协议\n' +
					'6、端口放行：进入服务器控制台【防火窗/安全组】放行指定端口号，或者放行全部TCP协议\n' +
					'7、框架服务器ip:端口号\n例：http://127.0.0.1:8886\n把【127.0.0.1】和【8886】修改成自己的\n\n错误信息：'+(data.msg || '未知错误');
				showToast(tmp, 'error');
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
		}
	});
}
function batch_qq(){
	var id = $('#login_api_test').val();
	var num = $('#protocol_num').val();
	if(id==-1){
		return false;
	}
	if(num==''){
		showToast('协议数量,不能为空', 'error');
		return false;
	}
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=batch_qq',
		data : {id:id,num:num},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			// 根据返回的code值决定Toast类型
			if (data.code == -1) {
				showToast(data.msg, 'error');
			} else {
				showToast(data.msg, 'success');
				$("#tmp_list_protocol").empty();
				var pid = data.id.split('-');
				for(var i in pid){
					$("#tmp_list_protocol").append('<tr id="row'+pid[i]+'">' +
						'<td style="min-width:120px;"><input type="hidden" name="pid[]" value="'+pid[i]+'">'+pid[i]+'</td>' +
						'<td style="min-width:120px;"><input type="text" class="form-control" name="p_name[]" placeholder="填写协议名称"></td>' +
						'<td><span class="btn btn-danger btn-sm" onclick="del_tr(\'row'+pid[i]+'\')">移除</span></td>' +
						'</tr>');
				}
				$('#form1').show();
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
var g_tr_num = 0;
function add_tr(){
	g_tr_num = document.getElementById("tmp_list_protocol").getElementsByTagName("tr").length;
	g_tr_num++;
	$("#tmp_list_protocol").append('<tr id="row'+g_tr_num+'">' +
		'<td style="min-width:120px;"><input type="number" class="form-control" name="pid[]" placeholder="填写协议ID"></td>' +
		'<td style="min-width:120px;"><input type="text" class="form-control" name="p_name[]" placeholder="填写协议名称"></td>' +
		'<td><span class="btn btn-danger btn-sm" onclick="del_tr(\'row'+g_tr_num+'\')">移除</span></td>' +
		'</tr>');
}
function del_tr(id){
	document.getElementById(id).parentNode.removeChild(document.getElementById(id));
}
function del_p(id){
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=del_p',
		data : {id:id},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, 'success');
			id = 'row_p'+id;
			document.getElementById(id).parentNode.removeChild(document.getElementById(id));
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
