<script setup lang="ts">
import { useAsyncState } from '@vueuse/core';
import ChangeRecordMenu from '../support/ChangeRecordManager.vue';
import { ChangeRecordService } from '../../core/services/change-record-service';
import { inject } from 'vue';
import { DeleteOutlined } from '@ant-design/icons-vue';

const changeRecordService = inject(ChangeRecordService.name) as ChangeRecordService;

const { state, isReady } = useAsyncState(() => changeRecordService.getList(), []);
const columns = [
    {
        title: 'Дата',
        dataIndex: 'changedAt',
        key: 'changedAt',
    },
    {
        title: 'Сумма',
        dataIndex: 'sum',
        key: 'sum',
    },
    {
        title: 'Группа расходов',
        dataIndex: 'spendingGroupName',
        key: 'spendingGroupName',
    },
    {
        title: 'Операция',
        dataIndex: 'operation',
        key: 'operation',
    }
]

const refreshData = () => {
    changeRecordService.getList().then(data => {
        state.value = data;
        isReady.value = true;
    });
}

const onDelete = (key: string) => {
    changeRecordService.deleteRecord(key)
    .then(() => {
        refreshData();
    })
}
</script>

<template>
    <div class="base-page">
        <h1>История изменений баланса</h1>
        <ChangeRecordMenu :refreshData="refreshData" />
        <a-table :dataSource="state" :columns="columns" v-if="isReady" >
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'operation'">
                    <a-popconfirm
                        v-if="state?.length"
                        title="Точно удалить?"
                        @confirm="onDelete(record.id)"
                    >
                        <a><DeleteOutlined /> Удалить</a>
                    </a-popconfirm>
                </template>
            </template>
        </a-table>
        <div v-else>
            <a-spin size="large" />
        </div>
    </div>
</template>

<style scoped>
.layout {
    
}
</style>