<template>
	<div class="billing-balances-container">
		<n-card class="balances-card">
			<ObjectList :options="options">
				<template #header-right>
					<n-button
						type="primary"
						:size="buttonSize"
						:loading="exporting"
						:block="isMobile"
						@click="exportToCsv"
					>
						<template #icon>
							<i-lucide-download class="h-4 w-4" />
						</template>
						{{ $t('Export') }}
					</n-button>
				</template>
			</ObjectList>
		</n-card>
	</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { NCard, NButton } from 'naive-ui';
import ObjectList from '../components/ObjectList.vue';
import { createResource } from 'jingrow-ui';
import { unparse } from 'papaparse';

const instance = getCurrentInstance();
const $t = instance?.appContext.config.globalProperties.$t || ((key) => key);
const $team = instance?.appContext.config.globalProperties.$team;

const exporting = ref(false);
const windowWidth = ref(window.innerWidth);

const isMobile = computed(() => windowWidth.value <= 768);
const buttonSize = computed(() => (isMobile.value ? 'medium' : 'medium'));

const props = defineProps(['tab']);
const options = computed(() => {
	return {
		pagetype: 'Balance Transaction',
		fields: ['type', 'source', 'invoice', 'description'],
		columns: [
			{
				label: $t('Time'),
				fieldname: 'creation',
				format(value) {
					return new Date(value).toLocaleString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit',
						hour: '2-digit',
						minute: '2-digit',
						second: '2-digit'
					}).replace(/\//g, '-');
				}
			},
			{
				label: $t('Description'),
				fieldname: 'description',
				format(value, row) {
					if (value !== null && value !== undefined) {
						return value;
					}
					
					if (row.type === 'Applied To Invoice' && row.invoice) {
						return $t('Applied to Invoice {invoice}', { invoice: row.invoice });
					}

					if (row.source === 'Prepaid Credits') {
						return $t('Balance Recharge');
					}

					if (row.source === 'Free Credits') {
						return $t('Free Credits');
					}

					return row.amount < 0 ? row.type : row.source;
				}
			},
			{
				label: $t('Amount'),
				fieldname: 'amount',
				align: 'right',
				format: formatCurrency
			},
			{
				label: $t('Balance'),
				fieldname: 'ending_balance',
				align: 'right',
				format: formatCurrency
			}
		],
		filters: {
			pagestatus: 1,
			team: $team.name
		},
		orderBy: 'creation desc'
	};
});

// 创建导出资源
const exportResource = createResource({
	url: 'jcloud.api.billing.get_balance_transactions',
	onSuccess: handleExportSuccess,
	onError: handleExportError
});

function formatCurrency(value) {
	if (value === 0) {
		return '';
	}
	const $format = instance?.appContext.config.globalProperties.$format;
	return $format?.userCurrency(value) || value;
}

function formatDate(dateString) {
	return new Date(dateString).toLocaleString('zh-CN', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit'
	}).replace(/\//g, '-');
}

function exportToCsv() {
	exporting.value = true;
	exportResource.submit({
		page: 1,
		page_size: 1000
	});
}

function handleExportSuccess(response) {
	const transactions = response.transactions || [];
	
	// 定义CSV字段
	const fields = [
		$t('Time'),
		$t('Description'),
		$t('Amount'),
		$t('Balance')
	];
	
	// 准备数据
	const csvData = transactions.map(row => {
		// 优先使用原始描述，如果存在的话
		let description = row.description;
		
		// 如果描述不存在，则使用备用逻辑
		if (!description) {
			if (row.type === 'Applied To Invoice' && row.invoice) {
				description = $t('Applied to Invoice {invoice}', { invoice: row.invoice });
			} else if (row.source === 'Prepaid Credits') {
				description = $t('Balance Recharge');
			} else if (row.source === 'Free Credits') {
				description = $t('Free Credits');
			} else {
				description = row.amount < 0 ? row.type : row.source;
			}
		}
		
		return [
			formatDate(row.creation),
			description,
			row.amount,
			row.ending_balance
		];
	});
	
	// 添加表头
	csvData.unshift(fields);
	
	// 生成CSV
	let csv = unparse(csvData);
	
	// 添加BOM以支持中文
	csv = '\uFEFF' + csv;
	
	// 触发下载
	const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
	const today = new Date().toISOString().split('T')[0];
	const filename = `${$t('Balance Records')}-${today}.csv`;
	const link = document.createElement('a');
	link.href = URL.createObjectURL(blob);
	link.download = filename;
	link.click();
	URL.revokeObjectURL(link.href);
	
	exporting.value = false;
}

function handleExportError(error) {
	console.error($t('Failed to export data'), error);
	exporting.value = false;
}

function handleResize() {
	windowWidth.value = window.innerWidth;
}

onMounted(() => {
	handleResize();
	window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
	window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.billing-balances-container {
	padding: 24px;
	width: 100%;
}

.balances-card {
	border-radius: 12px;
	box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

@media (max-width: 768px) {
	.billing-balances-container {
		padding: 16px;
	}
}
</style>