<script setup>
import { ref, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import useNotify from 'src/composables/useNotify';
import { useValidator } from 'src/composables/useValidator';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import FetchData from 'src/components/FetchData.vue';
import { watch } from 'vue';
import { onMounted } from 'vue';
const $props = defineProps({
    clients: {
        type: Array,
        required: true,
    },
    promise: {
        type: Function,
        required: true,
    },
    selectedRows: {
        type: Boolean,
    },
});

const { selectedRows } = toRefs($props);
const { notify } = useNotify();
const { t } = useI18n();
const validationsStore = useValidator();
const campaignParams = ref(null);
const campaignsOptions = ref(null);
const moreFields = ref([]);
const popupProxyRef = ref(null);
const upcomingOptions = ref(null);
const campaignChange = ({ name }) => {
    const campaign = campaignsOptions.value.find((c) => c.code === name);
    handleDates(campaign);
};
const handleDates = (campaign) => {
    const from = new Date(campaign.dated);
    from.setDate(from.getDate() - campaign.scopeDays);
    campaignParams.value = {
        code: campaign.code,
        from: from,
        to: campaign.dated,
    };
};
watch(selectedRows, () => {
    handleDates(upcomingOptions.value);
});
const onSubmit = async () => {
    try {
        const data = {
            clients: $props.clients.map((item) => item.id),
            from: campaignParams.value.from,
            to: campaignParams.value.to,
        };
        const params = JSON.stringify(data);
        await axios.post('ClientConsumptionQueues', { params });

        notify('globals.dataSaved', 'positive');
        popupProxyRef.value.hide();
    } catch (error) {
        notify(error.message, 'negative');
    }
};

onMounted(async () => {
    const { models } = validationsStore;
    const properties = models.Item?.properties || {};
    const _moreFields = ['valentinesDay', 'mothersDay', 'allSaints'];

    _moreFields.forEach((field) => {
        let prop = properties[field];
        const label = t(`params.${field}`);
        moreFields.value.push({
            name: field,
            label,
            type: prop ? prop.type : null,
        });
    });
});
</script>

<template>
    <FetchData
        url="Campaigns/latest"
        @on-fetch="(data) => (campaignsOptions = data)"
        :filter="{ fields: ['id', 'code', 'dated'], order: 'code ASC', limit: 30 }"
        auto-load
    />
    <FetchData
        url="Campaigns/upcoming"
        @on-fetch="(data) => (upcomingOptions = data)"
        auto-load
    />
    <QBtn color="primary" icon="show_chart" :disable="!selectedRows">
        <QPopupProxy ref="popupProxyRef">
            <QCard class="column q-pa-md">
                <span class="text-body1 q-mb-sm">{{ t('Campaign consumption') }}</span>
                <VnRow>
                    <VnSelect
                        :options="moreFields"
                        option-value="code"
                        option-label="label"
                        v-model="campaignParams.code"
                        :label="t('Campaign')"
                        @update:model-value="campaignChange"
                    />
                </VnRow>
                <VnRow>
                    <VnInputDate v-model="campaignParams.from" :label="t('From')" />
                    <VnInputDate v-model="campaignParams.to" :label="t('To')" />
                </VnRow>
                <div class="q-mt-lg row justify-end">
                    <QBtn
                        :label="t('globals.cancel')"
                        color="primary"
                        flat
                        class="q-mr-md"
                        v-close-popup
                    />
                    <QBtn
                        :label="t('globals.save')"
                        type="submit"
                        color="primary"
                        @click="onSubmit()"
                    />
                </div>
            </QCard>
        </QPopupProxy>
        <QTooltip>{{ t('Campaign consumption') }}</QTooltip>
    </QBtn>
</template>

<i18n>
    en:
        params:
            valentinesDay: Valentine's Day
            mothersDay: Mother's Day
            allSaints: All Saints' Day
    es:
        params:
            valentinesDay: Día de San Valentín
            mothersDay: Día de la Madre
            allSaints: Día de Todos los Santos
        Campaign consumption: Consumo campaña
        Campaign: Campaña
        From: Desde
        To: Hasta
</i18n>
