<template>
    <div class="row h-100 parentContainer">
        <div class="col-12" style="min-height: 20px;">
            <loading-component style="height: 20px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
        </div>

        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3>{{ componentTitle }}</h3>
                    <div class="row m-b-10 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
                        <div class="col">
                            <small class="bold fs-10 text-danger">{{error}}</small>
                        </div>
                    </div>
                    <div class="text-right">
                        <button class="btn btn-xs btn-outline-success b-rad-none m-r-5" @click="downloadInvoiceMapped">
                            Download Invoices Mapped
                        </button>
                    </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover">
                    <thead>
                        <tr>
                            <th v-for="header in tableHeaders" :key="header">{{ header }}</th>
                        </tr>
                    </thead>
                    <tbody v-show="!isLoading">
                        <tr v-for="(item, index) in queueStore.getListData(section)" :key="index">
                            <td>{{index+1}}</td>
                            <td>{{item.doc_no }}</td>
                            <td>{{item.date}}</td>
                            <td>{{item.debtor_code }}</td>
                            <td>{{item.debtor_name}}</td>
                            <td>{{item.shipping_info}}</td>
                            <td>{{item.net_total}}</td>
                            <td>{{item.cancelled}}</td>
                            <td>{{item.mapped_status}}</td>
                            <td>{{item.mapped_result_reference}}</td>
                            <td>{{item.payment_received_date}}</td>
                        </tr>
                    </tbody>
                    </table>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">

                </div>
            </div>
        </div>

        <div class="col-12">
            <pagination-component :section="section" class="mb-5" ref="pagination"></pagination-component>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { ref, computed, watch, onMounted } from 'vue';
    import { useQueueStore } from '@/stores/queue';
    import { useCrudStore } from '@/stores/crud';
    import { useRequest } from '@/composables/useRequest';

    const props = defineProps<{
        files: any;
        type: string;
        section: string;
    }>();

    const queueStore = useQueueStore();
    const crudStore = useCrudStore();
    const { submit } = useRequest();

    const isLoading = ref(false);
    const error = ref('');
    const importedDate = ref<string | null>(null);
    const componentTitle = ref('Imported Invoices Mapped');
    const tableHeaders = ref(['No','Doc No','Date','Debtor Code','Debtor Name','Shipping Info','Net Total','Cancelled','Mapped Status','Mapped Reference No','Payment Received Date']);

    const pendingQueue = computed(() => {
        return queueStore.isInCompleteQueue(props.section);
    });

    watch(pendingQueue, (inComplete) => {
        if (inComplete) {
            importInvoice();
        }
    });

    onMounted(() => {
        queueStore.updateListQueue({ name: props.section });
    });

    const importInvoice = () => {
        isLoading.value = true;

        submit(
            (window as any).route('api.import_invoices.upload'),
            'post',
            props.section,
            true,
            true,
            {
                files: props.files
            },
            {
                successHandler: (response: any) => {
                    queueStore.setListComplete({ name: props.section, data: response.payload.data });
                    importedDate.value = response.payload.importedDate;
                    isLoading.value = false;
                },
                errorHandler: (err: any) => {
                    isLoading.value = false;
                    error.value = err.message;
                }
            }
        );
    };

    const downloadInvoiceMapped = () => {
        if (!importedDate.value) return;

        const arrDateTime = importedDate.value.split(" ");
        const fileName = 'importInvoiceMapping';
        const url = (window as any).route('importedInvoiceMapped.export') + '?date=' + arrDateTime[0] + '&time=' + arrDateTime[1] + '&fileName=' + fileName;

        if ((window as any).LARAVEL_VAPOR_ENABLED) {
            crudStore.crudRequest({ endpoint: url, method: 'get' })
                .then(async (response: Response) => {
                    if (response.ok) {
                        const data = await response.json();
                        if (data.src) {
                            window.open(data.src, '_blank');
                        }
                    }
                });
        } else {
            window.open(url, '_blank');
        }
    };
</script>

