var isgoods = false;
var goodsdata;
var allGoodsData = null;
var allClassData = null;
var show_apiclass = 0;
var pagesize = 30;
var page = 1;
var confirmCallback = null;
var exportCallback = null;

// 显示消息模态框
function showMessageModal(message, type) {
    var iconHtml = '';
    if (type === 'success') {
        iconHtml = '<i class="fas fa-check-circle text-green-500 text-4xl"></i>';
    } else if (type === 'error') {
        iconHtml = '<i class="fas fa-times-circle text-red-500 text-4xl"></i>';
    } else {
        iconHtml = '<i class="fas fa-info-circle text-blue-500 text-4xl"></i>';
    }
    document.getElementById('messageIcon').innerHTML = iconHtml;
    document.getElementById('messageText').innerHTML = message;
    document.getElementById('messageModal').classList.remove('hidden');
}

// 关闭消息模态框
function closeMessageModal() {
    document.getElementById('messageModal').classList.add('hidden');
}

// 显示确认模态框
function showConfirmModal(message, callback) {
    document.getElementById('confirmText').innerHTML = message;
    confirmCallback = callback;
    document.getElementById('confirmModal').classList.remove('hidden');
}

// 关闭确认模态框
function closeConfirmModal() {
    document.getElementById('confirmModal').classList.add('hidden');
    confirmCallback = null;
}

// 确认删除按钮点击事件
document.getElementById('confirmYesBtn').addEventListener('click', function() {
    if (confirmCallback) {
        confirmCallback();
    }
    closeConfirmModal();
});

// 显示导出模态框
function showExportModal(callback) {
    exportCallback = callback;
    document.getElementById('exportModal').classList.remove('hidden');
}

// 关闭导出模态框
function closeExportModal() {
    document.getElementById('exportModal').classList.add('hidden');
    exportCallback = null;
}

// 导出按钮点击事件
document.getElementById('exportYesBtn').addEventListener('click', function() {
    if (exportCallback) {
        var type = document.getElementById('exportType').value;
        exportCallback(type);
    }
    closeExportModal();
});

// 打开生成模态框（每次打开重置表单）
function openGenerateModal() {
    document.getElementById('generateModal').classList.remove('hidden');
    $('#need').val('');
    $('input[name="num"]').val('1');
    // 重置按钮状态
    var btn = document.getElementById('addKamiBtn');
    if (btn) {
        btn.disabled = false;
        btn.innerHTML = '确定';
    }
    loadCategories();
}

// 关闭生成模态框
function closeGenerateModal() {
    document.getElementById('generateModal').classList.add('hidden');
}

// 打开结果模态框
function openResultModal(kamiData) {
    document.getElementById('txt_km').value = kamiData;
    document.getElementById('resultModal').classList.remove('hidden');
}

// 关闭结果模态框
function closeResultModal() {
    document.getElementById('resultModal').classList.add('hidden');
    get_list(page, pagesize);
}

// 复制卡密
function copyKami() {
    var kamiText = document.getElementById('txt_km').value;
    var textarea = document.getElementById('txt_km');
    textarea.select();
    textarea.setSelectionRange(0, 99999);
    
    try {
        var successful = document.execCommand('copy');
        if (successful) {
            showMessageModal('复制成功', 'success');
        } else {
            showMessageModal('复制失败', 'error');
        }
    } catch (err) {
        showMessageModal('复制失败', 'error');
    }
    
    window.getSelection().removeAllRanges();
}

// 当打开生成模态框时加载分类
function loadCategories() {
    if(isgoods === false){
        get_goods();
    } else {
        initVersionDisplay();
    }
}

function initVersionDisplay() {
    var version = $('#km-version').val();
    if(version == 'qzone'){
        $('#kami-cid-container').hide();
        $('#kami-goods-container').show();
        $('#kami-time-container').hide();
        loadGoodsByVersion();
    } else {
        $('#kami-cid-container').show();
        $('#kami-goods-container').show();
        $('#kami-time-container').hide();
        loadGoodsByVersion();
    }
}

function get_goods(){
	showLoading();
	$.ajax({
		type : 'GET',
		url : 'ajax.php?act=get_goods',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			isgoods = true;
			allGoodsData = data.data;
			allClassData = data.class;
			show_apiclass = data.show_apiclass || 0;
			loadGoodsByVersion();
		},
		error:function(data){
			hideLoading();
			showMessageModal('服务器错误', 'error');
			return false;
		}
	});
}
function canGenerateKamiGoods(item, version){
	if(!item || parseInt(item.limit_once || 0) === 1){
		return false;
	}
	if(version == 'cloud') return (item.version == 'cloud' || item.version == '' || !item.version) && item.version != 'qzone';
	if(version == 'dg') return item.version == 'dg';
	if(version == 'cloud_all') return item.version == 'cloud_all' || item.version == 'all';
	if(version == 'dg_all') return item.version == 'dg_all';
	if(version == 'tri_all') return item.version == 'tri_all';
	if(version == 'qzone') return item.version == 'qzone';
	return false;
}
function loadGoodsByVersion(){
	var version = $('#km-version').val();
	$('#cid').html('');
	goodsdata = {};

	if(version == 'qzone'){
		$('#kami-cid-container').hide();
		$('#kami-goods-container').show();
		$('#kami-time-container').hide();
		var qzoneGoods = [];
		$.each(allGoodsData, function(typeId, items){
			if(items){
				items.forEach(function(item){
					if(canGenerateKamiGoods(item, 'qzone')){
						qzoneGoods.push(item);
					}
				});
			}
		});
		goodsdata['qzone'] = qzoneGoods;
		$('select[name="goods"]').html('');
		if(qzoneGoods.length > 0){
			qzoneGoods.forEach(function(obj){
				$('select[name="goods"]').append('<option value="'+ obj.id +'" price="'+ obj.price +'" time_type="'+ (obj.time_type || 1) +'" time_num="'+ (obj.num || 30) +'">'+ obj.name +'</option>');
			});
		}else{
			$('select[name="goods"]').append('<option value="">暂无商品</option>');
		}
		get_point();
		return;
	}

	if(show_apiclass == 1){
		$('#kami-cid-container').hide();
		// 合并所有可见分类的商品
		goodsdata['all_merged'] = [];
		$.each(allGoodsData, function(typeId, items){
			if(typeId == 'qzone' || !items) return true;
			items.forEach(function(item){
				if(canGenerateKamiGoods(item, version)){
					var exists = goodsdata['all_merged'].some(function(g){ return g.id == item.id; });
					if(!exists) goodsdata['all_merged'].push(item);
				}
			});
		});
	}else{
		$('#kami-cid-container').show();
	}
	$('#kami-goods-container').show();
	$('#kami-time-container').hide();
	$.each(allClassData, function(i, value){
		if(value.id != 99 && allGoodsData[value.id]){
			var filteredGoods = allGoodsData[value.id].filter(function(item){
				return canGenerateKamiGoods(item, version);
			});
			if(filteredGoods.length > 0){
				if(show_apiclass == 0) goodsdata[value.id] = filteredGoods;
				$('#cid').append('<option value="'+value.id+'">'+value.name+'</option>');
			}
		}
	});

	if(show_apiclass == 1){
		goods_point('all_merged');
	}else{
		goods_point();
	}
}

function goods_point(customType){
	var cid = customType || $('#cid').val();
	$('select[name="goods"]').html('');
	if(!goodsdata[cid] || goodsdata[cid].length == 0){
		$('select[name="goods"]').append('<option value="">该分类下没有商品</option>');
		$('#need').val('暂无商品');
		return;
	}
	$.each(goodsdata[cid],function(k,v){
		$('select[name="goods"]').append('<option value="'+ v.id +'" price="'+ v.price +'" desc="'+ encodeURI(v.desc || '') +'">'+ v.name +'</option>');
	});
	get_point();
}
function get_point(){
	var version = $('#km-version').val();
	if(version == 'qzone'){
		var selectedOption = $('select[name="goods"]').find("option:selected");
		if(selectedOption.length && selectedOption.attr('price')){
			var price = parseFloat(selectedOption.attr("price")) || 0;
			var num = parseInt($('input[name="num"]').val()) || 1;
			var total = (num * price).toFixed(2);
			$('#need').val('￥ '+ total +' 元');
		}else{
			$('#need').val('暂无商品');
		}
		return;
	}
	var price = parseFloat($('select[name="goods"]').find("option:selected").attr("price")) || 0;
	var num = parseInt($('input[name="num"]').val()) || 1;
	var total = (num * price).toFixed(2);
	$('#need').val('￥ '+ total +' 元');
}
function num_money(){
	get_point();
}
function add_kami(){
	var btn = document.getElementById('addKamiBtn');
	if (btn.disabled) return;
	btn.disabled = true;
	btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>生成中...';
	showLoading();
	$.ajax({
		type : 'POST',
		data : $('#km_form').serialize(),
		url : 'ajax.php?act=add_kami',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			btn.disabled = false;
			btn.innerHTML = '确定';
			if(data.code == 1){
				closeGenerateModal();
				openResultModal(data.km);
			}else{
				showMessageModal(data.msg, 'error');
			}
		},
		error:function(data){
			hideLoading();
			btn.disabled = false;
			btn.innerHTML = '确定';
			showMessageModal('服务器错误', 'error');
			return false;
		}
	});
}
$(document).ready(function() {
    get_list(page,pagesize);
	$('#page').change(function(){
		page = $('#page').val();
		get_list(page,pagesize);
	});
	$('#cid').change(function(){
		goods_point();
	});
	$('#km-version').change(function(){
		loadGoodsByVersion();
	});
	$('select[name="goods"]').change(function(){
		get_point();
	});
	$('input[name="time_num"]').change(function(){
		get_point();
	});
	$('select[name="time"]').change(function(){
		get_point();
	});
});
function get_list(p, ps){
	var kw = $("input[name='kw']").val();
	var type = $("select[name='type']").val();
	showLoading();
	$.ajax({
		type : 'POST',
		data : {pagesize:ps, page:p, kw:kw, type:type},
		url : 'ajax.php?act=get_kami',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			adddata(data.data);
			$('#total').html(data.total);

			// 更新分页信息
			var totalPage = data.end || 1;
			var currentPage = data.page || 1;
			$('#totalPages').text(totalPage);
			$('#currentPage').text(currentPage);

			// 更新上一页/下一页按钮状态
			$('#prevPage').prop('disabled', currentPage <= 1);
			$('#nextPage').prop('disabled', currentPage >= totalPage);

			// 更新页码下拉框
			if(totalPage >= 1){
				page = parseInt(p);  // 更新全局变量
				$('#page').html('');
				var start = currentPage - 10 > 1 ? currentPage - 10 : 1;
				var endPage = currentPage + 10 < totalPage ? currentPage + 10 : totalPage;
				for(var i = start; i <= currentPage; i++){
				    $('#page').append('<option value="'+ i +'">' + i + '</option>');
				}
				for(var i = currentPage + 1; i <= endPage; i++){
				    $('#page').append('<option value="'+ i +'">' + i + '</option>');
				}
				$('#page').val(currentPage);
			}
			if(data.read_num >= 1){
				$("#readAll").show();
			}
		},
		error:function(data){
			hideLoading();
			showMessageModal('服务器错误', 'error');
			return false;
		}
	});
}
function adddata(data){
	$("#list").empty();
	var versionMap = {'cloud': '云端版', 'dg': '代挂版', 'qzone': '秒赞版', 'cloud_all': '云端·秒赞', 'dg_all': '代挂·秒赞', 'tri_all': '三版通用', 'all': '云端·秒赞'};
	$.each(data, function(i,v){
		var statusClass = v.isuse == "1" ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700';
		var statusText = v.isuse == "1" ? '已使用' : '未使用';
		var versionText = versionMap[v.version] || '云端版';
		var versionClass = v.version == 'qzone' ? 'bg-orange-100 text-orange-700' : ((v.version == 'all' || v.version == 'cloud_all' || v.version == 'dg_all' || v.version == 'tri_all') ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700');
		var row = '<tr class="hover:bg-gray-50">' +
			'<td class="px-4 py-3 text-sm font-medium text-gray-800 whitespace-nowrap">' + v.km + '</td>' +
			'<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + versionClass + ' rounded">' + versionText + '</span></td>' +
			'<td class="px-4 py-3 text-sm whitespace-nowrap">' + v.name + '</td>' +
			'<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + statusClass + ' rounded">' + statusText + '</span></td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">￥' + v.rmb + '</td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + (v.qq == null ? '-' : v.qq) + '</td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + (v.usetime == null ? '-' : v.usetime) + '</td>' +
			'<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + v.addtime + '</td>' +
			'<td class="px-4 py-3 whitespace-nowrap"><button type="button" onclick="del(' + v.id + ',' + v.isuse + ')" class="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 whitespace-nowrap">删除</button></td>' +
			'</tr>';
		$("#list").append(row);
	});
}
function del(id,isuse){
	if(isuse == 1){
		var str = '确定删除吗？';
	}else{
		var str = '确定删除吗？<br>未使用的卡密将会退回余额';
	}
	showConfirmModal(str, function() {
		showLoading();
		$.ajax({
			type : 'POST',
			url : 'ajax.php?act=del_kami',
			data : {id:id},
			dataType : 'json',
			success : function(data) {
				hideLoading();
				if(data.code == 1){
					showMessageModal(data.msg, 'success');
					get_list(page,pagesize);
				}else{
					showMessageModal(data.msg, 'error');
				}
			},
			error:function(data){
				hideLoading();
				showMessageModal('请求超时', 'error');
			}
		});
	});
}
function searchOrder(){
	get_list(page,pagesize);
}
function daochu(id){
	showExportModal(function(type) {
		showLoading();
		$.ajax({
			type : 'POST',
			url : 'ajax.php?act=saveas_km',
			data : {id:id,type:type,kw:$('input[name="kw"]').val(),type2:$('select[name="type"]').val()},
			dataType : 'json',
			success : function(data) {
				hideLoading();
				if(data.code == 1){
					var txt = data.km;
					if (txt.indexOf('<br/>') < 0) {
						txt = txt.replace(/\n/g, "\r\n");
					}
					var fileName = (new Date()).toISOString().substr(0, 10) + ".txt";
					var blob = new Blob([txt], {type: "text/plain;charset=utf-8"});
					saveAs(blob, fileName);
					showMessageModal('导出成功', 'success');
				}else if(data.code == 2){
					showMessageModal(data.msg, 'error');
				}else{
					showMessageModal(data.msg, 'error');
				}
			},
			error:function(data){
				hideLoading();
				showMessageModal('请求超时', 'error');
			}
		});
	});
}
function qk(type){
	showLoading();
	$.ajax({
		type : 'POST',
		data : {kami_qk_type:type},
		url : 'ajax.php?act=kami_qk',
		dataType : 'json',
		success : function(data) {
			hideLoading();
			showMessageModal(data.msg, data.code == 1 ? 'success' : 'error');
			if(data.code == 1){
				get_list(page,pagesize);
			}
		},
		error:function(data){
			hideLoading();
			showMessageModal('服务器错误', 'error');
			return false;
		}
	});
}
