<template>
	<div class="p-5">
		<ObjectList :options="options" />
	</div>
</template>

<script>
import { jingrowRequest } from 'jingrow-ui';
import ObjectList from '../components/ObjectList.vue';
import { icon } from '../utils/components';

export default {
	name: 'BillingMpesaInvoices',
	data() {
		return {
			invoices: [],
			loading: false,
			errorMessage: null,
		};
	},
	components: {
		ObjectList,
	},
	methods: {
		async fetchInvoices() {
			this.loading = true;
			try {
				const response = await jingrowRequest({
					url: '/api/method/jcloud.api.regional_payments.mpesa.utils.display_invoices_by_partner',
					method: 'GET',
				});
				this.invoices = response;
			} catch (error) {
				this.errorMessage = `加载发票失败。${error}`;
			} finally {
				this.loading = false;
			}
		},
		formatCurrency(value) {
			return new Intl.NumberFormat('en-US', {
				style: 'currency',
				currency: 'Ksh',
			}).format(value);
		},
	},
	computed: {
		options() {
			return {
				pagetype: 'Mpesa Payment Record',
				fields: [
					'name',
					'posting_date',
					'amount',
					'local_invoice',
					'payment_partner',
					'amount_usd',
					'exchange_rate',
				],
				columns: [
					{
						label: '发票名称',
						fieldname: 'name',
						width: 1,
					},
					{
						label: '日期',
						fieldname: 'posting_date',
						width: 0.7,
					},
					{
						label: '金额',
						fieldname: 'amount',
						align: 'center',
						width: 0.6,
					},
					{
						label: '金额 (美元)',
						fieldname: 'amount_usd',
						align: 'center',
						width: 0.6,
					},
					{
						label: '汇率',
						fieldname: 'exchange_rate',
						align: 'center',
						width: 0.6,
					},
					{
						label: '支付合作伙伴',
						fieldname: 'payment_partner',
					},
					{
						label: '',
						type: 'Button',
						align: 'right',
						Button: ({ row }) => {
							if (row.local_invoice) {
								return {
									label: '下载发票',
									slots: {
										prefix: icon('download'),
									},
									onClick: () => {
										window.open(row.local_invoice);
									},
								};
							}
						},
					},
				],
				orderBy: 'posting_date desc',
			};
		},
	},
	mounted() {
		this.fetchInvoices();
	},
};
</script>