<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 id="accordion">
                    <div class="card">
                        <div class="card-header" id="headingOne">
                        <h5 class="mb-0">
                            <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                            Filters
                            </button>
                        </h5>
                        </div>
                        <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
                            <div class="card-group" style="margin-bottom: 0px;">
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">Pay For</h3>
                                        <div class="card-tools">
                                            <div class="form-check" v-for="(match, index) in matches" :key="index">
                                                <input class="form-check-input" type="checkbox" :value="match" :id="'match'+index" v-model="selected.matches">
                                                <label class="form-check-label" :for="'match' + index">
                                                    {{ match }}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card" style="margin-top: 0px">
                                    <div class="card-header">
                                        <h3 class="card-title">Date</h3>
                                        <div class="form-check" v-for="(day, index) in days" :key="day">
                                            <input class="form-check-input" type="checkbox" :id="'day'+index" :value="day" v-model="selected.days">
                                            <label class="form-check-label" :for="'day'+index">
                                                {{ day }}
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end mb-2">
                                <button type="button" class="btn btn-sm btn-primary" @click="fetchList(true)">
                                    <i class="fa fa-plus-square"></i>
                                    Filter
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 v-if="queueStore.getListData(section)[0] !== undefined" class="card-title">{{ (queueStore.getListData(section)[0] as any).account_name }} - {{ (queueStore.getListData(section)[0] as any).account_number }},{{ (queueStore.getListData(section)[0] as any).account_type }} </h3><br/>
                        <h3 v-if="queueStore.getListData(section)[0] !== undefined" class="card-title">{{ new Date((queueStore.getListData(section)[0] as any).account_statement_date_from).toDateString() }} -> {{ new Date((queueStore.getListData(section)[0] as any).account_statement_date_to).toDateString() }}</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body table-responsive p-0">
                        <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Posting Date</th>
                                <th>Description 1</th>
                                <th>Description 2</th>
                                <th>Description 3</th>
                                <th>Description 4</th>
                                <th>Description 5</th>
                                <th>Amount</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody v-show="!isLoading">
                            <tr v-for="item in queueStore.getListData(section)" :key="item.id">
                                <td>{{item.id}}</td>
                                <td>{{item.posting_date}}</td>
                                <td>{{item.transaction_description_1}}</td>
                                <td>{{item.transaction_description_2}}</td>
                                <td>{{item.transaction_description_3}}</td>
                                <td>{{item.transaction_description_4}}</td>
                                <td>{{item.transaction_description_5}}</td>
                                <td>{{item.amount}}</td>
                                <td>
                                    <a href="#">
                                        <i class="fa fa-edit blue requestModal" data-type="editSingleItem" @click="editModal({item})"></i>
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                        </table>
                    </div>
                    <!-- /.card-body -->
                    <div class="card-footer">

                    </div>
                </div>
                <!-- /.card -->
            </div>

            <div class="col-12">
                <modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="editSingleItem">
                    <edit-single-item-in-list-component v-if="editData != null" :data="editData" :section="'editSingleItem'" class="text-left"></edit-single-item-in-list-component>
                </modal-component>
            </div>

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

</template>

<script setup lang="ts">
    import { ref, reactive, computed, watch, onMounted } from 'vue';
    import { useQueueStore } from '@/stores/queue';
    import { useRequest } from '@/composables/useRequest';
    import EditSingleItemInListComponent from "@/components/accounting/elements/EditSingleItemInListComponent.vue";
    import PaginationComponent from '@/components/general/elements/PaginationComponent.vue';

    const props = defineProps<{
        statement: number;
    }>();

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

    const section = 'statementTransactionsDetails';
    const isLoading = ref(false);
    const editData = ref<any>(null);
    const paginationRef = ref<InstanceType<typeof PaginationComponent> | null>(null);

    const matches = ['exchange', 'shipping', 'none'];
    const selected = reactive({
        matches: [] as string[],
        days: [] as string[]
    });

    const filters = ref<Record<string, any>>({ 'per_page': 10, order_by: { column: 'id', DESC: true } });
    const page = ref(1);
    const days = ref<string[]>([]);

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

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

    watch(selected, () => {
        // pay_for
        if (selected.matches.length > 0) {
            const newArr = selected.matches.slice();
            const index = newArr.indexOf('none');
            if (index > -1) {
                newArr.splice(index, 1, '');
            }
            filters.value.pay_for_in = newArr;
        } else {
            delete filters.value.pay_for_in;
        }

        // date
        if (selected.days.length > 0) {
            filters.value.date_in = selected.days.slice();
        } else {
            delete filters.value.date_in;
        }
    }, { deep: true });

    const setDecoratorDefault = () => {
        filters.value = queueStore.normalizeListFilters(filters.value);
    };

    const fetchList = (isUpdate = false) => {
        isLoading.value = true;
        if (!isUpdate) {
            const listDecorators = queueStore.getListDetails(section);
            if (!listDecorators) {
                return;
            }
            page.value = listDecorators.page;
        }

        const url = (window as any).route('api.accounting.statement.details', props.statement) + '?page=' + page.value + '&filters=' + JSON.stringify(filters.value);

        submit(
            url,
            'get',
            section,
            true,
            true,
            undefined,
            {
                successHandler: (response: any) => {
                    queueStore.setListComplete({ name: section, data: response.payload.data });
                    if (paginationRef.value) {
                        // paginationRef.value.makePagination(response.payload.meta, response.payload.links + '&filters=' + JSON.stringify(filters.value));
                        paginationRef.value.makePagination(response.payload.meta);
                    }
                    generateDays();
                    isLoading.value = false;
                }
            }
        );
    };

    const editModal = (param: { item: any }) => {
        editData.value = param.item;
    };

    const generateDays = () => {
        const listData = queueStore.getListData(section);
        if (listData[0] !== undefined) {
            const startDate = new Date((listData[0] as any).account_statement_date_from);
            const endDate = new Date((listData[0] as any).account_statement_date_to);
            const generatedDays: string[] = [];
            for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
                generatedDays.push(formatDate(new Date(d)));
            }
            days.value = generatedDays;
        }
    };

    const formatDate = (date: Date) => {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
    };

    onMounted(() => {
        setDecoratorDefault();
        queueStore.updateListQueue({ name: section, page: 1, filters: { ...filters.value } });
    });
</script>

