<template>
    <div class="row m-b-20">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="row m-l-0 m-r-0 bg-master-light padding-10">
                        <div class="col-12 col-md mb-2 mb-md-0 pointer">
                            <div class="row h-100">
                                <div class="col">
                                    <div class="bg-white bg-hover-complete h-100 btn btn-xs btn-outline-none btn-block text-left b-rad-none p-t-0 p-b-0 p-l-15 p-r-15" @click="selectedDocumentStatus = !selectedDocumentStatus">
                                        <div class="row h-100">
                                            <div class="col fs-9 d-flex align-items-center flex-column" style="padding-top: 7px; padding-bottom: 4px;">
                                                <label class="all-caps w-100 m-b-0" style="font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; font-weight: 500;">Document Type</label>
                                                <span class="w-100 fs-14">{{parameters.type.replaceAll('_', ' ')}}</span>
                                            </div>
                                            <div class="col-auto b-l b-grey">
                                                <div class="row h-100 align-items-center">
                                                    <div class="col">
                                                        <i class="fa" :class="[{'fa-angle-down': !selectedDocumentStatus}, {'fa-angle-up': selectedDocumentStatus}]"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="relative w-100">
                                        <div class="absolute w-100 b-l b-b b-r b-grey" :class="[{'hide': !selectedDocumentStatus}]" style="top: 100%; right: 0; z-index: 1;">
                                            <div class="row text-left no-margin bg-white">
                                                <div class="col no-padding">
                                                    <div class="row no-margin" v-for="document in documents" :key="document">
                                                        <div class="col b-grey p-t-10 p-b-10 pointer hover-t-10 p-b-10 b-a" :class="[{'bg-primary-light': document === parameters.type}, {'text-white': document === parameters.type}, {'b-primary': document === parameters.type}, {'hover-primary': document !== parameters.type}, {'pointer': document !== parameters.type}]" @click="updateDocumentType(document)">
                                                            <div class="row align-items-center justify-content-center">
                                                                <div class="col">
                                                                    <div class="font-heading fs-10">{{document.replaceAll('_', ' ')}}</div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col">
                            <validation-wrapper-component selectable :validator="v$.parameters.supplier">
                                <label>Supplier</label>
                                <selectable-component :endpoint="route('api.company.list')+'?filters={%22business_type%22:3}'" section="supplierListSection" valueColumn="id" :labelColumn="['name']" v-model="parameters.supplier"></selectable-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md mb-2 mb-md-0">
                            <validation-wrapper-component :validator="v$.parameters.startDate">
                                <label class="all-caps">Start Date</label>
                                <date-picker-component :parameters="parameters" v-model.lazy="parameters.startDate"></date-picker-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md mb-2 mb-md-0">
                            <validation-wrapper-component :validator="v$.parameters.endDate">
                                <label class="all-caps">End Date</label>
                                <date-picker-component :parameters="parameters" v-model.lazy="parameters.endDate"></date-picker-component>
                            </validation-wrapper-component>
                        </div>
                        <div class="col-12 col-md-auto d-flex justify-content-center align-items-center">
                            <button type="button" class="btn btn-lg btn-primary fs-11 w-100" @click="submitSearch()">Download</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRequest } from '@/composables/useRequest';
import useVuelidate from '@vuelidate/core';
import { required } from '@vuelidate/validators';
import route from '@/general/functions/router';
import ValidationWrapperComponent from '@/components/general/forms/ValidationWrapperComponent.vue';
import SelectableComponent from '@/components/general/forms/SelectableComponent.vue';
import DatePickerComponent from '@/components/general/forms/DatePickerComponent.vue';

const props = defineProps<{
    section?: string;
}>();

const { submit } = useRequest();

const parameters = ref({
    startDate: '',
    endDate: '',
    type: 'INVOICE',
    supplier: null as null | string | number
});

const documents = ref([
    'INVOICE',
    'PURCHASE_ORDER',
    'DELIVER_ORDER',
    'SUPPLIER_DELIVER_ORDER',
    'INVOICE + PO + DO',
    'INVOICE + PO + DO + SDO'
]);

const selectedDocumentStatus = ref(false);

const rules = {
    parameters: {
        startDate: { required },
        endDate: { required },
        type: { required },
        supplier: {}
    }
};

const v$ = useVuelidate(rules, { parameters });

const updateDocumentType = (documentType: string) => {
    parameters.value.type = documentType;
    selectedDocumentStatus.value = !selectedDocumentStatus.value;
};

const successHandler = (response: any) => {
    if (window.LARAVEL_VAPOR_ENABLED) {
        if (response.src) {
            window.open(response.src, '_blank');
        }
    }
};

const submitSearch = async () => {
    if (!(await v$.value.$validate())) return;
    
    const params = `?type=${parameters.value.type}&startDate=${parameters.value.startDate}&endDate=${parameters.value.endDate}&supplier=${parameters.value.supplier || ''}`;
    
    if (window.LARAVEL_VAPOR_ENABLED) {
        submit(route('documents.download') + params, 'get', props.section, false, false, undefined, { successHandler });
    } else {
        window.open(route('documents.download') + params, '_blank');
    }
};
</script>
