var isgetdata = $('#isgetdata').val();
var biz = $('#biz').val() || 'cloud';
var pagesize = 30;
var page = 1;
var currentDelId = 0; // 当前要删除的分类ID
var currentDelBiz = 'cloud';
$(document).ready(function() {
	if(isgetdata == 1){
		get_list(page,pagesize);
	}
	$('#page').change(function(){
		page = $('#page').val();
		get_list(page,pagesize);
	});
});

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_login_class',
		dataType : 'json',
		success : function(data) {
				hideLoading();
				adddata(data.data);
			$('#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');
		}
	});
}
function adddata(data){
	$("#list").empty();
	$.each(data, function(i,v){
		var rowBiz = v.biz || biz || 'cloud';
		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 statusHtml = v.active == 0 ? 
			'<button type="button" onclick="edit_login_class(\'status\',' + v.id + ',0,0,1,\'' + rowBiz + '\')" class="px-2 py-1 text-xs font-medium text-green-700 bg-green-50 hover:bg-green-100 rounded-lg transition-all duration-200">显示中</button>' : 
			'<button type="button" onclick="edit_login_class(\'status\',' + v.id + ',0,0,0,\'' + rowBiz + '\')" class="px-2 py-1 text-xs font-medium text-red-700 bg-red-50 hover:bg-red-100 rounded-lg transition-all duration-200">隐藏中</button>';
		
		var tmp = '<tr class="hover:bg-gray-50 transition-colors duration-150">' +
			'<td class="px-2 py-2 whitespace-nowrap">' +
				'<button type="button" onclick="sort_show()" class="text-gray-600 hover:text-blue-600 mr-1 transition-colors duration-200">' +
					'<i class="fa fa-sort"></i>' +
				'</button>' +
				'<span class="text-xs font-medium text-gray-900">' + v.id + '</span>' +
			'</td>' +
			'<td class="px-2 py-2 whitespace-nowrap">' + bizBadge + '</td>' +
			'<td class="px-2 py-2 min-w-[140px]">' +
				'<input type="text" class="w-full px-2 py-1 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-xs transition-all duration-200" value="' + v.name + '" id="name' + v.id + '" placeholder="输入分类名称">' +
			'</td>' +
			'<td class="px-2 py-2 min-w-[80px]">' +
				'<input type="number" class="w-full px-2 py-1 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-xs transition-all duration-200" value="' + v.free + '" id="free' + v.id + '" placeholder="填写0收费">' +
			'</td>' +
			'<td class="px-2 py-2 whitespace-nowrap">' + statusHtml + '</td>' +
			'<td class="px-2 py-2 whitespace-nowrap">' +
				'<a href="./qqlist.php?biz=' + encodeURIComponent(rowBiz) + '&kw=' + v.id + '&type=4" class="px-2 py-1 text-xs font-medium text-white bg-green-600 hover:bg-green-700 rounded-lg transition-all duration-200 mr-1">QQ列表</a>' +
				(biz_transfer_btn(v.id, rowBiz, v.name)) +
				'<button type="button" onclick="edit_login_class(\'set\',' + v.id + ', document.getElementById(\'name' + v.id + '\').value, document.getElementById(\'free' + v.id + '\').value,0,\'' + rowBiz + '\')" class="px-2 py-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-all duration-200 mr-1">修改</button>' +
				(v.id == 1000 ? '' : '<button type="button" onclick="edit_login_class(\'del\',' + v.id + ',0,0,0,\'' + rowBiz + '\')" class="px-2 py-1 text-xs font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition-all duration-200">删除</button>') +
			'</td>' +
		'</tr>';
		
		$("#list").append(tmp);
	});
	
	var addBizSelect = '';
	if(biz == 'all'){
		addBizSelect = '<select id="add_biz" class="px-2 py-1 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:border-transparent">'+
			'<option value="cloud">云端</option>'+
			'<option value="dg">代挂</option>'+
		'</select>';
	}
	var tmp = '<tr class="hover:bg-gray-50 transition-colors duration-150">' +
		'<td colspan="5" class="px-2 py-2">' +
			'<div class="flex items-center space-x-2">' +
				(addBizSelect ? addBizSelect : '') +
				'<input type="text" class="w-40 px-2 py-1 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-xs transition-all duration-200" id="name" placeholder="输入分类名称">' +
				'<button type="button" onclick="add_class()" class="min-w-[80px] px-3 py-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-all duration-200 whitespace-nowrap">添加分类</button>' +
			'</div>' +
		'</td>' +
		'<td class="px-2 py-2"></td>' +
	'</tr>';
	
	$("#list").append(tmp);
}

function biz_transfer_btn(id, rowBiz, name){
	if(rowBiz !== 'cloud' && rowBiz !== 'dg') return '';
	var safeBiz = String(rowBiz || '').replace(/"/g, '&quot;');
	var safeName = String(name || '').replace(/"/g, '&quot;');
	return '<button type="button" data-biz="' + safeBiz + '" data-cid="' + id + '" data-name="' + safeName + '" onclick="showBizTransferModalFromBtn(this)" class="px-2 py-1 text-xs font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-all duration-200 mr-1">版本转移</button>';
}

function showBizTransferModalFromBtn(btn){
	if(!btn) return;
	var srcBiz = btn.getAttribute('data-biz') || '';
	var srcCid = parseInt(btn.getAttribute('data-cid') || '0', 10);
	var srcName = btn.getAttribute('data-name') || '';
	showBizTransferModal(srcCid, srcBiz, srcName);
}

function showBizTransferModal(srcCid, srcBiz, srcName){
	$('#biz_transfer_src_biz').val(srcBiz);
	$('#biz_transfer_src_cid').val(srcCid);
	$('#biz_transfer_src_text').text((srcBiz === 'dg' ? '代挂' : '云端') + ' / ' + srcCid + ' / ' + (srcName || ''));
	var dstBiz = (srcBiz === 'dg') ? 'cloud' : 'dg';
	$('#biz_transfer_dst_biz').val(dstBiz);
	$('#biz_transfer_modal').modal('show');
}

function confirmBizTransfer(){
	var srcBiz = String($('#biz_transfer_src_biz').val() || '');
	var srcCid = parseInt($('#biz_transfer_src_cid').val() || '0', 10);
	var dstBiz = String($('#biz_transfer_dst_biz').val() || '');
	if((srcBiz !== 'cloud' && srcBiz !== 'dg') || (dstBiz !== 'cloud' && dstBiz !== 'dg')){
		showToast('参数错误', 'error');
		return;
	}
	if(!srcCid) return;
	if(srcBiz === dstBiz){
		showToast('目标版本不能相同', 'error');
		return;
	}
	showLoading();
	$.ajax({
		type: 'POST',
		url: 'ajax.php?act=transfer_login_class_biz',
		data: {src_biz: srcBiz, src_cid: srcCid, dst_biz: dstBiz},
		dataType: 'json',
		success: function(res){
			hideLoading();
			showToast(res.msg || (res.code == 1 ? '转移成功' : '转移失败'), res.code == 1 ? 'success' : 'error', 8000);
			if(res.code == 1){
				setTimeout(function(){ location.reload(); }, 2500);
			}
		},
		error: function(){
			hideLoading();
			showToast('服务器错误', 'error');
		}
	});
}
function add_class(){
	var name = $('#name').val();
	if(name == ''){
		showToast('分类名称不能为空', 'error');
		return false;
	}
	var postBiz = biz;
	if(postBiz == 'all'){
		postBiz = $('#add_biz').val() || 'cloud';
	}
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=add_login_class',
		data : {name:name,biz:postBiz},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, data.code == 1 ? 'success' : 'error');
			if(data.code == 1){
				location.reload();
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
function edit_login_class(type,id,name='',free=0,zt=0,rowBiz=''){
	if(type == 'set' && name == ''){
		showToast('分类名称不能为空', 'error');
		return false;
	}
	var postBiz = rowBiz || biz || 'cloud';
	if(postBiz == 'all') postBiz = 'cloud';
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=edit_login_class',
		data : {id:id,name:name,type:type,free:free,zt:zt,biz:postBiz},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			if(data.code == -2){
				// 需要二次确认删除，显示模态框
				currentDelId = data.id;
				currentDelBiz = postBiz;
				$('#del_class_message').text(data.msg + '，确定要删除该分类吗？');
				$('#del_class_modal').modal('show');
			}else{
				showToast(data.msg, data.code == 1 ? 'success' : 'error');
				if(data.code == 1){
					location.reload();
				}
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}

function confirm_del_class(){
	$('#del_class_modal').modal('hide');
	del_login_class_force(currentDelId, currentDelBiz);
}

function del_login_class_force(id, rowBiz){
	var postBiz = rowBiz || biz || 'cloud';
	if(postBiz == 'all') postBiz = 'cloud';
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=del_login_class_force',
		data : {id:id,biz:postBiz},
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showToast(data.msg, data.code == 1 ? 'success' : 'error');
			if(data.code == 1){
				location.reload();
			}
		},
		error:function(data){
			hideLoading();
			showToast('服务器错误', 'error');
			return false;
		}
	});
}
function sort_show(){
	if(biz == 'all'){
		showToast('请先选择业务后再排序', 'error');
		return;
	}
	showLoading();
	$.ajax({
		type : 'GET',
		url : 'ajax.php?act=login_class_sort&biz=' + encodeURIComponent(biz),
		dataType : 'json',
		success : function(data){
			hideLoading();
			var tmp = '';
			$.each(data, function(i,v){
				tmp += '<div class="mb-2 flex items-center space-x-2">' +
					'<div class="flex-1 bg-gray-50 px-3 py-2 rounded-lg flex items-center shadow-sm">' +
						'<span class="text-xs font-medium text-gray-900">' + v.name + '</span>' +
					'</div>' +
					'<input type="number" class="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-xs font-medium transition-all duration-200 hover:shadow-sm" name="sort[' + v.id + ']" value="' + v.sort + '">' +
				'</div>';
			});
			$('#sort_content').html('<form id="form1" class="space-y-2">' + tmp + '</form><p class="mt-2 text-xs font-medium text-red-600">数值 越少越靠前</p>');
			$('#sort_modal').modal('show');
		}
	});
}

function confirm_sort(){
	$('#sort_modal').modal('hide');
	showLoading();
	$.ajax({
		type : 'POST',
		url : 'ajax.php?act=edit_login_class_sort',
		data : $('#form1').serialize() + '&biz=' + encodeURIComponent(biz),
		dataType : 'json',
		success : function(data) {
			hideLoading();
			if(data.code == 1){
				showToast(data.msg, 'success');
				get_list(page,pagesize);
			}else{
				showToast(data.msg, 'error');
			}
		},
		error:function(data){
			hideLoading();
			showToast('请求超时', 'error');
		}
	});
}
